我正在使用Entity Framework 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”实例,则必须指定“订单”实例.
问题:如何使ol.Order属性可选(在某些情况下为null)?可能吗?
解决方法
OrderLine上现在需要Order的原因是因为您在流畅的API代码中使用了Hasrequired()来配置关联.我们只需将其更改为HasOptional,如下面的代码所示:
- this.HasOptional(ol => ol.Order)
- .WithMany(o => o.OrderLines)
- .HasForeignKey(ol => ol.OrderId);
这将基本上使OrderLines.OrderId列成为DB中的(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而无需为它们指定订单.