How can I use the database view in entity framework code first,
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:
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 ());
}