【问题标题】:Generate DBContext from models [Code First]从模型生成 DBContext [代码优先]
【发布时间】:2016-01-30 12:27:53
【问题描述】:
我还没有数据库,我已经创建了在文件夹中注释的模型,但是当尝试使用命令 dnx ef migrations add Initial 创建初始迁移时,我给了我 error No DbContext was found。
我认为它会从我添加到模型中的注释生成 DBContext,我的问题是 - 是否有命令从我的注释模型生成 DBContext 或者我必须编写 DBContext没有数据库时手动操作?
【问题讨论】:
-
您应该添加一个具有 DBContext 定义的文件,例如public class MyDBContext : DbContext { DbSet<User> Users { get; set; } DbSet<Order> Orders { get; set; } ... }。您可以在一个程序中为不同的数据库定义多个上下文。您应该使用附加参数来指定需要创建的 dbcontext。您可以从the old answer下载演示项目。
-
-
标签:
entity-framework
entity-framework-core
【解决方案1】:
当我使用 Code First 时,我必须手动创建 DBContext(而且我认为它不会自动创建任何 DbContext)。所以你创建了你的模型吗?之后我创建DbContext 类(我总是为此DAL 文件夹创建)并在这个类中:
public class YourDBContextClassName : DbContext
{
public YourDBContextClassName () : base("YourDBContextClassName ")
{
}
public DbSet<YourModelName> YourName { get; set; }
//other models
//with YourName if you have for example Book Model then it could be something like this:
public DbSet<Book> Books { get; set; }
}
此base 来自Web.config 文件,名称必须与connectionStrings 中的名称匹配
<connectionStrings>
<add name="YourDBContextClassName " connectionString="Data Source=(localdb);Initial Catalog=YourCatalogDB;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
当然,connectionString 在您的情况下可能会有所不同。