2

我在 .Net 4 上使用 EF 5

我有以下模型:

public class Order
{

    [Key]
    public int Id { get; set; }
    public string OrderId { get; set; }

    public Address BillingAddress { get; set; }
    public Address DeliveryAddress { get; set; }
    public ICollection<OrderLine> OrderLines { get; set; }
}

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

    public string Description { get; set; }
    public decimal UnitPrice { get; set; }
    public int Quantity { get; set; }
    public string SKU { get; set; }
    public decimal ShippingCost { get; set; }
    public decimal Tax { get; set; }
}

public class Address
{
    [Key]
    public int Id { get; set; }
    public string Addressee { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string AddressLine3 { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string Country { get; set; }
    public string Postcode { get; set; }
}

和型号配置:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>().HasMany(x => x.OrderLines).WithRequired().WillCascadeOnDelete();
    modelBuilder.Entity<Order>().HasOptional(x => x.BillingAddress).WithOptionalDependent().WillCascadeOnDelete();
    modelBuilder.Entity<Order>().HasOptional(x => x.DeliveryAddress).WithOptionalDependent().WillCascadeOnDelete();

    base.OnModelCreating(modelBuilder);
}

当我运行以下查询时,我得到带有19 个连接的 sql,这对于简单的关系来说似乎过多

context.Orders
       .Where(x => x.OrderId == orderId)
       .Include(x => x.OrderLines)
       .Include(x => x.BillingAddress)
       .Include(x => x.DeliveryAddress)
       .FirstOrDefault();

难道我做错了什么?格式化 linq 查询以优化生成的 SQL 是否有不同的格式?

编辑:

这是实际查询:https ://gist.github.com/4278014

4

1 回答 1

1

我认为问题出WithOptionalDependent在帐单和送货地址上。这会在地址和订单之间创建 1:1 的关系,即使表是为 1:many 关系设置的。

如果您更改配置以WithMany改用:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>().HasMany(x => x.OrderLines).WithRequired().WillCascadeOnDelete();
    modelBuilder.Entity<Order>().HasOptional(x => x.BillingAddress).WithMany().WillCascadeOnDelete();
    modelBuilder.Entity<Order>().HasOptional(x => x.DeliveryAddress).WithMany().WillCascadeOnDelete();

    base.OnModelCreating(modelBuilder);
}

查询要简单得多,基本上等同于:

...
FROM [Orders]
LEFT OUTER JOIN [Addresses] As B ON [Orders].[BillingAddress_Id] = B.[Id]
LEFT OUTER JOIN [Addresses] As D ON [Orders].[DeliveryAddress_Id] = D.[Id]
LEFT OUTER JOIN [OrderLines] ON [Orders].[Id] = [OrderLines].[Order_Id]
于 2012-12-13T18:47:36.500 回答