Use Views in Entity Framework

后端 未结 2 1106
耶瑟儿~
耶瑟儿~ 2021-01-14 23:46

I am using Entity Framework on a project, but am finding the large queries, especially those which use LEFT joins, to be very tedious to write, and hard to debug.

Is

相关标签:
2条回答
  • 2021-01-15 00:27

    First create your view.
    Update Your .edmx File.
    then use like this.

    using (ManishTempEntities obj = new ManishTempEntities())
    {
         var a = obj.View_1.ToList();
    }
    
    0 讨论(0)
  • 2021-01-15 00:39

    the question is not very clear but there is no absolute right or wrong in Software. it all depends on your case.

    there is native support for views in ef core but there is no native support for views in EF < 6. at least not in the current latest version 6.3. there is, however, a work around to this. in database first you would create your view via sql normally and when you reverse engineer your database, EF will treat your view as a normal model and will allow you to consume it regularly as you would do in a normal table scenario. in Code First it's a bit more tedious. you would create a POCO object that maps to the columns in your view. notice that you need to include an Id in this POCO class. for example

    public class ViewPOCO
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public Guid Id {get;set;}
        public string ViewColumn1 {get;set;}
        ... etc.
    }
    

    you would add this POCO class in your DbContext

    public class MyDbContext : DbContext
    {
      public virtual DbSet<ViewPOCO> MyView {get;set;}
    }
    

    now you will normally apply the command of adding migration through the package manager console

     Add-Migration <MigrationName> <ConnectionString and provider Name>
    

    now in the migration up and down you will notice that EF treats your Model as table. you would clear all of this and write your own sql to add/alter the view in the up and drop the view in the down method using the Sql function.

     public override void Up()
     {
        Sql("CREATE OR ALTER VIEW <ViewName> AS SELECT NEWID() AS Id, ...");
     }
     public override void Down()
     {
       Sql("DROP VIEW <ViewName>");
     }
    
    0 讨论(0)
提交回复
热议问题