永远不会调用OnModelCreating [英] OnModelCreating is never called
本文介绍了永远不会调用OnModelCreating的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开始使用实体框架。
问题是从来没有调用过我的OnModelCreating方法。
I am starting work with entity framework. Problem is that my OnModelCreating method is never called.
这是我的上下文类:
public class TestContext : DbContext
{
public TestContext()
: base("name=TestDBConnectionString")
{ }
public DbSet<WorkItem> WorkItems { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
连接字符串
<add name="TestDBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=TestDB;Integrated Security=true"
providerName="System.Data.SqlClient"/>
我希望在致电时进入OnModelCreating:
I expect to go into OnModelCreating when I call:
using (var context = new TestContext())
{
}
我在哪里弄错了?
推荐答案
尝试添加一个
赞
using (var context = new TestContext())
{
context.WorkItem.Add(new WorkItem()); //Construct valid entity
context.SaveChanges();
}
根据默认策略,如果没有,它将尝试创建数据库。不存在。否则至少会引发异常。
By default strategy, it will try to create a database, if it doesn't exist. Or at least will throw an exception.
或者您可以强制其在启动时创建数据库
Or you can force it to create database at start up
context.Database.Initialize(true);
context.Database.Initialize(true);
https://msdn.microsoft.com/en-us/library/ system.data.entity.database.initialize(v = vs.113).aspx
这篇关于永远不会调用OnModelCreating的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文