如何在 MVC3 和实体框架上使用 Code First 将另一个表添加到我的数据库?
我有一个使用 Code First 范例创建的 MVC3 项目,它运行得很好。我创建了一个继承自 DBContext 的模型,添加了连接字符串,然后我可以写入表等。
不过,我似乎无法弄清楚如何使用 Code First 将另一个表添加到数据库中。添加指向同一数据库的另一个连接字符串不起作用。简单地添加另一个类,为其创建 DBContext,然后添加某些内容并将其保存到新上下文中是行不通的。
如何仅使用代码自动将新表添加到数据库?我当前的 web.config 看起来像这样:
<add name="PersonDBContext"
connectionString="Data Source=|DataDirectory|PersonData.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
我的工作模型看起来像这样:
public class Person
{
public int ID { get; set; }
public string name { get; set; }
public string country { get; set; }
public string gender { get; set; }
}
public class PersonDBContext : DbContext
{
public DbSet<Person> People { get; set; }
}
最后我想创建什么:
public class Dog
{
public int ID { get; set; }
public string name { get; set; }
public string breed { get; set; }
}
public class DogDBContext : DbContext
{
public DbSet<Dog> Dogs { get; set; }
}
I have an MVC3 project I created using the Code First paradigm and it works great. I created a model inheriting from DBContext, added the connection string, and I can write to the table and all that.
I can't seem to figure out how to add another table to the database using Code First, though. Adding another connection string that points to the same database doesn't work. Simply adding another class, creating a DBContext for it, and then adding and saving something to the new context doesn't work.
How do I add a new table to the database automatically using just code? My current web.config looks like this:
<add name="PersonDBContext"
connectionString="Data Source=|DataDirectory|PersonData.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
My working model looks like this:
public class Person
{
public int ID { get; set; }
public string name { get; set; }
public string country { get; set; }
public string gender { get; set; }
}
public class PersonDBContext : DbContext
{
public DbSet<Person> People { get; set; }
}
And finally what I want to create:
public class Dog
{
public int ID { get; set; }
public string name { get; set; }
public string breed { get; set; }
}
public class DogDBContext : DbContext
{
public DbSet<Dog> Dogs { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不为这两个类创建单一上下文?
Why wouldn't you create single context for both classes?
只需使用:
Just use: