我对实体框架有疑问。我正在使用代码首先接近但它不是创建数据库。使用global.asax中的以下代码抛出错误:
using (resimupDeneme.Data.DataContext db = new DataContext())
{
db.Database.CreateIfNotExists();
}
这是我的图片类:
public class foto
{
public int fotoId { get; set; }
[Required(ErrorMessage="fotoğraf yolu zorunludur")]
[DataType(DataType.ImageUrl)]
public string uzanti{ get; set; }
}
我的上下文类:
public class DataContext : DbContext
{
public DataContext() //i find this codes from internet for a solution for my problem but it is not worked
: base("DataContext")
{
Database.SetInitializer<DataContext>(new CreateDatabaseIfNotExists<DataContext>());
}
public DbSet<foto> fotos { get; set; }
}
答案 0 :(得分:1)
你在评论中说:
现在不是扔车(有趣)但是当我试图看数据库时 在sql server对象资源管理器上它不存在
您是否真的将Sql Server作为目标使用?
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
默认情况下,它定位于localdb
<defaultConnectionFactory
type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,
EntityFramework">
你的web.config中是否有一个名为"DataContext"
的连接字符串,如果是,它指向你的SqlServer实例?
...
除此之外,你多次做同样的事情。从using
。
db.Database.CreateIfNotExists();
从DataContext中提取它:
Database.SetInitializer<DataContext>(new CreateDatabaseIfNotExists<DataContext>());
并将其直接放入Application_Start()
或使用静态Config方法创建一个EfDatabaseConfig类,并从Application_Start()
调用它。
EfDatabaseConfig.Configure();
或者只使用web.config:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
<contexts>
<context type=" Blogging.BlogContext, MyAssembly">
<databaseInitializer type="System.Data.Entity.CreateDatabaseIfNotExists`1[[Blogging.BlogContext, MyAssembly]], EntityFramework" />
</context>
</contexts>
</entityFramework>