如何首先使用EF代码映射现有的sql server视图

Mon*_*kar 5 entity-framework

我是EF的新手并且首先学习EF代码.我正在寻找一个知识,首先用EF代码映射现有的sql server视图.我用POCO映射了我的视图,但得到了以下错误.

当我尝试从视图中获取数据时,抛出以下错误

附加信息:自创建数据库以来,支持'TestDBContext'上下文的模型已更改.考虑使用Code First Migrations来更新数据库

我的完整代码如下

public class TestDBContext : DbContext
    {
        public TestDBContext()
            : base("name=TestDBContext")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new vwCustomerConfiguration());
        }

        public DbSet<vwCustomer> vwCustomer { get; set; }
    }

public class vwCustomerConfiguration : EntityTypeConfiguration<vwCustomer>
{
    public vwCustomerConfiguration()
    {
        this.HasKey(t => t.CustomerID);
        this.ToTable("vwCustomer");
    }
}

      public class vwCustomer
        {
            public int CustomerID { get; set; }
            public string FirstName { get; set; }

        }
Run Code Online (Sandbox Code Playgroud)

这样我试图加载数据.

    using (var db = new TestDBContext())
    {
        var listMyViews = db.vwCustomer.ToList();
    }
Run Code Online (Sandbox Code Playgroud)

指导我在错误抛出的代码中缺少的内容.谢谢

UPDATE1

当我发出Add-Migration"My_vwCustomer"时,我看到新的迁移代码添加如下.似乎没有正在等待的迁移.

   public partial class My_vwCustomer : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.vwCustomers",
                c => new
                    {
                        CustomerID = c.Int(nullable: false, identity: true),
                        FirstName = c.String(),
                    })
                .PrimaryKey(t => t.CustomerID);

        }

        public override void Down()
        {
            DropTable("dbo.vwCustomers");
        }
    }
Run Code Online (Sandbox Code Playgroud)

Sam*_*ath 10

OP的反馈:

当我使用ADO.Net Entity模型向导生成视图时,一切正常.

你可以这样做,如下所示.

注意:我从这篇文章中选择了1到4 .

  1. 为视图创建一个POCO类; 例如FooView
  2. DbSetDbContext类中添加属性
  3. 使用FooViewConfiguration文件为视图设置不同的名称(使用ToTable("Foo");在构造函数中)或设置特定属性

    public class FooViewConfiguration : EntityTypeConfiguration<FooView>      
    {
       public FooViewConfiguration()
       {
        this.HasKey(t => t.Id);
        this.ToTable("myView");
      }
    
    Run Code Online (Sandbox Code Playgroud)

    }

  4. 将FooViewConfiguration文件添加到modelBuilder,例如,使上下文的OnModelCreating方法失效:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new FooViewConfiguration ());
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. 根据上面的配置,现在你的表是 this.ToTable("myView");.换句话说myView.

    这是在桌子EF query上检索.all the datamyView

    var listMyViews = yourDbContext.myView.ToList()

您的预测可能是这样的:

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