C#-EF CodeFirst-HasOptional属性创建新对象

时间:2018-10-28 03:04:55

标签: c# entity-framework ef-code-first

我有下一个带有映射的模型:

public partial class BPart
{
    public Guid Id { get; set; }
    [Required]
    public Part PartNumber { get; set; }
    [Required]
    public Revision Revision { get; set; }        
    public Assembly Assembly { get; set; }        
    public Vendor Vendor { get; set; }
    public double Qty { get; set; }
    [StringLength(100)]
    public string Unit { get; set; }
    public OrderState OrderState { get; set; }        
    public string AdditionalInformation { get; set; }
    public bool IsRemoved { get; set; }
    public BPart()
    {
        Id = Guid.Empty;
        Assembly = new Assembly();
        Vendor = new Vendor();
        OrderState = new OrderState();
    }
}

public BOMPartMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);
        // Properties
        this.Property(t => t.Qty);
        this.Property(t => t.Unit)
             .HasMaxLength(100);                      
        // Table & Column Mappings
        this.ToTable("BOMPart");
        this.Property(t => t.Id).HasColumnName("Id")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); ;
        this.Property(t => t.Qty).HasColumnName("Qty");
        this.Property(t => t.Unit).HasColumnName("Unit");
        this.Property(t => t.IsRemoved).HasColumnName("IsRemoved");
        this.Property(t => t.AdditionalInformation).HasColumnName("AdditionalInformation");
        this.HasRequired(t=>t.PartNumber)
            .WithMany(t=>t.BOMS)
            .Map(c => c.MapKey("PartReferenceId"));
        this.HasRequired(t => t.Revision)
            .WithMany(t => t.Parts)
            .Map(c => c.MapKey("RevisionReferenceId"));
        this.HasOptional(t => t.Assembly)
            .WithMany(t => t.Parts)
            .Map(c => c.MapKey("AssemblyReferenceId"));
        this.HasOptional(t => t.Vendor)
            .WithMany(t => t.OrderedParts)
            .Map(c => c.MapKey("VendorReferenceId"));
        this.HasOptional(t => t.OrderState)
            .WithMany(t => t.Parts)
            .Map(c => c.MapKey("OrderStateReferenceId"));
    }
}

当我使用NULLable OrderState和Vendor创建新的BOMPart对象时,EF也创建了可选对象(Vendor和OrderState)。保存之前我的对象看起来像:

BPart.Vendor = null
BPart.OrderState = null

我检查了数据库,并且此可选字段具有检查集市NULLABLE。但是我不知道为什么EF为可选字段创建新对象。

谢谢!

0 个答案:

没有答案