EF Code First Fluent映射:0-1到多个:HasOptional()WithMany()

时间:2013-09-07 16:47:07

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

我正在使用现有数据库的项目使用EF,而我坚持使用。我有2个奇数映射表(我相信它的0-1到很多)。部分问题是字段中可能存在垃圾,所以我希望它完全可以从nav属性中获取null。

TruckPart可选择与零件相关。 零件可以与0个或更多卡车零件相关(虽然我不需要在该方向上遍历关系)

我的EF关闭了,除了当我通过Include(“Part”)引入关系时,它使用INNER JOIN并且我需要它来使用LEFT JOIN。

类:

public class TruckPart
{
    public int TruckPartId { get; set; }
    public int PartId { get; set; }   
    public string Location { get; set; }
    public virtual Part Part { get; set; }
    // plus other fields
}

public class TruckPartMapping : EntityTypeConfiguration<TruckPart>
{
    public TruckPartMapping()
    {
        // Primary Key
       HasKey(t => t.TruckPartID);

       HasRequired(t => t.Part).WithMany().HasForeignKey(t => new { t.Location, t.PartID });
       //HasOptional(t => t.Part).WithMany().HasForeignKey(t => new { t.Location, t.PartID });
       //HasOptional(t => t.Part).WithMany().Map(t => t.MapKey("Location", "PartID"));
    }
}

public class Part
{
    public string Loc { get; set; }
    public int PartID { get; set; }
    // plus other fields
}

public class PartMapping : EntityTypeConfiguration<Part>
{
    public PartMapping()
    {
        // Primary Key
        HasKey(t => new { t.Loc, t.PartID});
    }
}

我尝试过HasOptional()而不是HasRequired(),但是我得到以下错误(我假设因为HasOptional()和HasForeignKey()没有相处)

System.Data.Entity.Edm.EdmAssociationType: 
    Multiplicity conflicts with the referential constraint in Role 
   'TruckPart_Part_Target' in relationship 'TruckPart_Part'. 
    Because all of the properties in the Dependent Role are non-nullable, 
    multiplicity of the Principal Role must be '1'.

我尝试用Map(MapKey)替换HasForeignKey但是我得到错误(我假设因为我已经有了这些属性):

 error 0019: Each property name in a type must be unique. 
             Property name 'Location' was already defined.
 error 0019: Each property name in a type must be unique. 
             Property name 'PartID' was already defined.

我甚至可以在EF中添加这种导航属性吗?

1 个答案:

答案 0 :(得分:4)

为了使关系成为可选关系,您需要TruckPart权利中的可空外键属性(加上HasOptional的映射):

public int? PartId { get; set; }