【发布时间】:2017-01-17 14:26:56
【问题描述】:
我是 EF 的新手,首先学习 EF 代码。我正在寻找一种知识来首先使用 EF 代码映射现有的 sql server 视图。我已经用 POCO 映射了我的视图,但出现以下错误。
当我尝试从视图中获取数据时抛出以下错误
附加信息:支持“TestDBContext”上下文的模型 自创建数据库以来已更改。考虑使用代码优先 迁移以更新数据库
我的完整代码如下
public class TestDBContext : DbContext
{
public TestDBContext()
: base("name=TestDBContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new vwCustomerConfiguration());
}
public DbSet<vwCustomer> vwCustomer { get; set; }
}
public class vwCustomerConfiguration : EntityTypeConfiguration<vwCustomer>
{
public vwCustomerConfiguration()
{
this.HasKey(t => t.CustomerID);
this.ToTable("vwCustomer");
}
}
public class vwCustomer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
}
这样我正在尝试加载数据。
using (var db = new TestDBContext())
{
var listMyViews = db.vwCustomer.ToList();
}
指导我在抛出错误的代码中缺少什么。谢谢
更新1
当我发出 Add-Migration "My_vwCustomer" 时,我看到添加了新的迁移代码,如下所示。似乎没有待处理的迁移。
public partial class My_vwCustomer : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.vwCustomers",
c => new
{
CustomerID = c.Int(nullable: false, identity: true),
FirstName = c.String(),
})
.PrimaryKey(t => t.CustomerID);
}
public override void Down()
{
DropTable("dbo.vwCustomers");
}
}
【问题讨论】:
-
我解决了迁移生成问题。 See my answer
-
为了防止为您的视图添加迁移,您可以在 DbContext 中使用
.ToView()而不是.ToTable(),在您的代码中将this.ToTable("vwCustomer");更改为this.ToView("vwCustomer");
标签: entity-framework