How to map exisiting sql server view with EF code first

后端 未结 2 1760
逝去的感伤
逝去的感伤 2021-01-02 23:19

i am fairly new in EF and learning EF code first. i am looking for a knowledge to map exisiting sql server view with EF code first. i have map my view with POCO but getting

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 23:58

    OP's Feedback :

    When i generate the view with ADO.Net Entity model wizard then everything works fine.

    You can do it as shown below.

    Note : I have picked the 1 to 4 from this post.

    1. Create a POCO class for the view; for example FooView
    2. Add the DbSet property in the DbContext class
    3. 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      
      {
         public FooViewConfiguration()
         {
          this.HasKey(t => t.Id);
          this.ToTable("myView");
        }
      

      }

    4. 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 ());
      }
      
    5. According to the above configuration,now your table is this.ToTable("myView");.In other words myView.

      Here is the EF query to retrieve all the data on the myView table.

      var listMyViews = yourDbContext.myView.ToList()

    Your projection may be like this :

    var query = yourDbContext.myView
            .Select(v=> new
            {
                ID = v.ID,
                EmpName = v.EmpName,
                Salary = v.Salary 
            }).ToList();
    

提交回复
热议问题