代码之家  ›  专栏  ›  技术社区  ›  djdd87

实体框架代码优先-急加载未按预期工作?

  •  11
  • djdd87  · 技术社区  · 14 年前

    public class Customer
    {
        public int Id {get;set;}
        public string Name {get;set;}
    
        public virtual ICollection<Order> Orders {get;set;}
    }
    
    public class Order
    {
        public int Id {get;set;} 
        public int CustomerId {get;set;}
        public int OrderTypeId {get;set;}
    
        public virtual OrderType Type {get;set;}
        public virtual Customer Customer {get;set;}
    } 
    
    public class OrderType 
    {
        public int Id {get;set;}
        public virtual ICollection<Order> Orders {get;set;}
    }
    

    问题是当我归还我的 ICollection<Order> 我要去接电话 Order 没关系,但是 OrderType 财产 订单

    Id:          1
    CustomerId:  1
    Customer:    Populated
    OrderTypeId: 3
    Type:        null        // Never returned
    

    我的映射代码如下所示:

    public void ConfigureOrder(ModelBuilder builder)
    {
        // Mapping from Order -> Customer
        builder.Entity<Order>()
            .HasRequired(x => x.Customer)
                .WithMany(x => x.Orders)
                    .HasConstraint((order, cust) => order.CustomerId == cust.Id);
    
        // Mapping from Order -> OrderType
        builder.Entity<Order>()
            .HasRequired(x => x.OrderType)
                .WithMany(x => x.Orders)
                    .HasConstraint((order, type) => order.OrderTypeId == type.Id);
    }
    

    然后在我的上下文中禁用了延迟加载:

    public Context(string connectionString)
        : base(connectionString)
    {
        ObjectContext.ContextOptions.LazyLoadingEnabled = false;
    }
    

    因此,要返回存储库中的数据,我使用 Include System.Data.Entity :

    var query = from item in context.Customers
                    .Include(x=> x.Orders)
                where item.Id == customerId
                select item;
    

    我之所以这么想是因为我不能具体说明 Orders.OrderType ,这就是问题所在,所以我尝试了一些变体:

    1 -> .Include(x=> x.Orders.FirstOrDefault().OrderType)
    2 -> .Include("Orders")
    3 -> .Include("Orders")
         .Include("Orders.OrderType")
    

    var query = from item in context.Orders
                    .Include(x=> x.OrderType)
                select item;
    

    此代码将正确返回订单中的OrderType。

    1 回复  |  直到 14 年前
        1
  •  22
  •   djdd87    14 年前

    哦,亲爱的。看来我是个十足的驴子。现在是17:45,反正我现在该回家了。

    我有两种方法:

    Get(int customerId)
    {
        // This was the method I was testing within
        var query = from item in context.Customers
                        .Include("Orders.OrderType")
                    select item;
    }
    
    Get(int customerId, int versionId)
    {
        // This was the method that was running
        var query = from item in context.Customers
                        .Include(item.Orders)
                    select item;
    }
    

    所以, "Orders.OrderType" 是正确的,尽管看起来很糟糕。我需要一些咖啡因。

    编辑:

    回到这个问题,includes最好的方法就是使用 System.Data.Entity

    .Include(x=> x.Orders.Select(o=> o.OrderType));