Views in the Code First Entity Framework

.net code-first database entity-framework view

Question

First, tell me how to utilize the database view in the entity framework code.

1
85
6/22/2015 6:54:10 PM

Accepted Answer

If, like me, you are simply interested in using views to connect entities from another database (in my case, an ERP) to entities related to your application, then map views just as you would a table. If the view is not updateable, you will undoubtedly get an exception if you attempt to update those entities. The process is the same as when dealing with entities that are normal (based on a table):

  1. Make a POCO class, like FooView, for the view.
  2. In the DbContext class, add the DbSet property.
  3. To change the view's name (using ToTable("Foo"); in the constructor) or to modify specific settings, use a FooViewConfiguration file.

    public class FooViewConfiguration : EntityTypeConfiguration<FooView>      
    {
        public FooViewConfiguration()
        {
            this.HasKey(t => t.Id);
            this.ToTable("myView");
        }
    }
    
  4. By way of the OnModelCreating method of the Context, for example, add the FooViewConfiguration file to the modelBuilder:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new FooViewConfiguration ());
    }
    
91
8/11/2014 6:12:06 AM

Popular Answer

It could be an update, but adding [Table("NameOfView")] to the top of the class should make it possible to utilize views with EF Code without having to go through all the hoops that everyone else must. Additionally, one of the columns has to be reported as a [key] column. To implement it, see my example code below.

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; }
    }
}

And this is how the situation seems.

using System.Data.Entity;

namespace SomeProject.Data
{
    public class DatabaseContext : DbContext
    {
        public DbSet<SomeView> SomeViews { get; set; }
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow