如何使用MVC3和实体框架上的代码在数据库中添加另一个表?
-
26-10-2019 - |
题
我有一个我使用代码第一个范式创建的MVC3项目,并且效果很好。我创建了一个从dbcontext继承的模型,添加了连接字符串,然后可以写入表格等。
不过,我似乎无法首先使用代码在数据库中添加另一个表。添加另一个指向同一数据库的连接字符串不起作用。只需添加另一个类,为其创建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; }
}
解决方案
您为什么不为两个类创建单个上下文?
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 Dog
{
public int ID { get; set; }
public string name { get; set; }
public string breed { get; set; }
}
public class ApplicationNameDBContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Dog> Dogs { get; set; }
}
其他提示
只是使用:
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 Dog
{
public int ID { get; set; }
public string name { get; set; }
public string breed { get; set; }
}
public class PersonDBContext : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Dog> Dogs { get; set; }
}
不隶属于 StackOverflow