我该如何在Entity Framework Code First中使用数据库视图?
我该如何在Entity Framework Code First中使用数据库视图?
如果你和我一样,只对将来自其他数据库(例如ERP)的实体映射到你的应用程序特定实体感兴趣,那么你可以像使用表格一样使用视图(以相同方式映射视图!)。当然,如果你尝试更新这些实体,如果视图不可更新,则会出现异常。
Create a POCO class for the view; for example FooView
Add the DbSet property in the DbContext class
Use a FooViewConfiguration file to set a different name for the view (using ToTable("Foo"); in the constructor) or to set particular properties
public class FooViewConfiguration : EntityTypeConfiguration<FooView>
{
public FooViewConfiguration()
{
this.HasKey(t => t.Id);
this.ToTable("myView");
}
}
Add the FooViewConfiguration file to the modelBuilder, for example overriding the OnModelCreating method of the Context:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new FooViewConfiguration ());
}
FooView
,并在我的 DbContext 类中添加一个 DbSet<FooView>
属性,然后 Entity Framework 就知道将其映射到视图上(假设我们有一个名为 dbo.Foo
的视图)? - Ashkan[Table("myView")]
,这可能比使用 EntityTypeConfiguration
更简单。 - Rudey这可能是一个更新提示,但要在EF Code First中使用视图,只需将 [Table("NameOfView")] 添加到类的顶部,一切都应该正常工作,无需像其他人一样经历所有麻烦。另外,您需要将其中一个列报告为[key]列。以下是我实现它的示例代码。
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SomeProject.Data
{
[Table("SomeView")]
public class SomeView
{
[Key]
public int NameID { get; set; }
public string Name { get; set; }
}
}
这是上下文的样子
using System.Data.Entity;
namespace SomeProject.Data
{
public class DatabaseContext : DbContext
{
public DbSet<SomeView> SomeViews { get; set; }
}
}
如果您只想要一堆非规范化的对象,那么您可以在您的DbContext
类中创建一个公共的只读IQueryable<TDenormolized>
属性。
在get
中,您返回一个Linq结果,将非规范化值投影到非规范化对象中。这可能比编写DB View更好,因为您在编程,不仅限于使用select
语句。此外,它是编译时类型安全的。
只需小心不要触发枚举,如ToList()
调用,这将打破延迟查询,您可能会从数据库获取100万条记录并在应用程序服务器上过滤它们。
我不知道这是否是正确的方法,但我尝试过,并且对我有效。
我用以下步骤解决了这个问题:数据库中已经存在名为'...'的对象。
OnModelCreating
中添加 if (IsMigration) modelBuilder.Ignore<ViewEntityName>();
。 - mBardos