开发者

Entity Framework CTP5, code-first. Optional navigation property

I'm using Entity Framework CTP5 (code-first) and I have two classes:

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

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

and

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; }
}

And I have the following configuration class for OrderLine class:

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);

        }
    }

Currently if you create an 'OrderLine' instance, you have to specify an 'Order' instance.

The question: how can I make ol.Order prope开发者_如何转开发rty optional (null in some cases)? Is it possible?


The reason Order is now required on OrderLine is because you used HasRequired() in your fluent API code to configure the association. We simply need to change that to HasOptional as the following code shows:

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

This will basically make the OrderLines.OrderId column as (INT, NULL) in the DB so that OrderLine records will be independent. We need to also reflect this change in the object model by make OrderId nullable on OrderLine class:

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

    public virtual Order Order { get; set; }
}

Now, you can save OrderLines without specifying an Order for them.


Not sure why you want to do that... but you can just change

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

to

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜