EF Core映射到具有复杂类型的SQL视图

时间:2019-07-31 16:23:35

标签: entity-framework sql-view ef-core-2.0 ef-core-2.1

我有一个需要与EF Core Code First一起使用的SQL视图。视图看起来像这样(简化):

    Select s.Id                 
           a.City                  
           a.State
    From   Shipment s
           Join Address a
             On s.AddressId = a.Id

我希望它映射到发货清单视图的POCO类:

        public class ShipmentListView
        {
            [Key]
            public int Id { get; set; }

            public Address Address { get; set; }
        }

        public class Address
        {
            public string City { get; set; }
            public string State { get; set; }
        }

Db Set:

    public virtual DbSet<ShipmentListView> ShipmentListView { get; set; }

如何映射规范化的View,以便可以在POCO Address的上下文中重用ShipmentListView

1 个答案:

答案 0 :(得分:0)

您可以使用下面的SQL View映射模型;

 protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity<ShipmentListView>(eb =>
        {
          eb.ToView("ShipmentListView");
        });
      base.OnModelCreating(modelBuilder);
    }

关于为该模型使用“相关”分类,您可以使用解决方法。

    public class ShipmentListView : Address
    {
        public int Id { get; set; }

        public Address Address { get; set; }
    }

    public class Address
    {
        public string City { get; set; }
        public string State { get; set; }
    }