【问题标题】:Entity Framework CTP5, code-first. Optional navigation property实体框架 CTP5,代码优先。可选的导航属性
【发布时间】:2010-12-30 08:21:19
【问题描述】:

我正在使用实体框架 CTP5(代码优先),我有两个类:

public class Order
{
   public int Id {get;set;}
   public decimal SomeOtherProperty1 {get;set;}

   //navigation property
   public virtual ICollection<OrderLine> OrderLines { get; set; }  
}

public class OrderLine
{
   public int Id {get;set;}
   public int OrderId {get;set;}
   public decimal SomeOtherProperty2 {get;set;}

   //navigation property
   public virtual Order Order { get; set; }
}

我有以下 OrderLine 类的配置类:

public partial class OrderLineMap : EntityTypeConfiguration<OrderLine>
    {
        public OrderLineMap()
        {
            this.HasKey(ol=> ol.Id);

            this.HasRequired(ol=> ol.Order)
                .WithMany(o => o.OrderLines)
                .HasForeignKey(ol=> ol.OrderId);

        }
    }

目前,如果您创建一个“OrderLine”实例,则必须指定一个“Order”实例。

问题:如何使 ol.Order 属性可选(在某些情况下为 null)?是否可以?

【问题讨论】:

    标签: asp.net entity-framework code-first


    【解决方案1】:

    OrderLine 现在需要 Order 的原因是您在 fluent API 代码中使用了HasRequired() 来配置关联。我们只需要将其更改为HasOptional,如下代码所示:

    this.HasOptional(ol => ol.Order)
        .WithMany(o => o.OrderLines)
        .HasForeignKey(ol => ol.OrderId);
    

    这基本上会使数据库中的 OrderLines.OrderId 列为 (INT, NULL),以便 OrderLine 记录是独立的。我们还需要通过在 OrderLine 类上设置 OrderId 为空来反映对象模型中的这种变化:

    public class OrderLine
    {
        public int Id { get; set; }
        public int? OrderId { get; set; }
        public decimal SomeOtherProperty2 { get; set; }
    
        public virtual Order Order { get; set; }
    }
    

    现在,您可以保存 OrderLines 而无需为其指定订单。

    【讨论】:

      【解决方案2】:

      不知道你为什么要这样做......但你可以改变

       this.HasRequired(ol=> ol.Order)
            .WithMany(o => o.OrderLines)
            .HasForeignKey(ol=> ol.OrderId);
      

       this.HasOptional(ol => ol.Order);
      

      【讨论】:

      • 但在这种情况下,导航属性 (ol.Order) 将不起作用。它不会加载适当的顺序(延迟加载)。
      • Order 属性是可选的或不是。如果它是可选的,那么它可以在数据库中为空。这正是我开始回答的原因:“不确定你为什么要这样做”。你到底想达到什么目标?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 2011-05-03
      • 2015-09-06
      • 1970-01-01
      相关资源
      最近更新 更多