If, like me, you are interested only in mapping entity coming from an other database (an erp in my case) to relate them to entities specific of your application, then you can use the views as you use a table (map the view in the same way!). Obviously, if you try to update that entities, you will get an exception if the view is not updatable.
The procedure is the same as in the case of normal (based on a table) entities:
- 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 ovveriding the OnModelCreating method of the Context:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new FooViewConfiguration ());
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…