Skip to main content
 首页 » 编程设计

c#之EF Code First Fluent 映射 : 0-1 to Many: HasOptional() WithMany()

2024年02月13日16duanxz

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

TruckPart 可以选择性地与 Part 相关。 一个零件可以与 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 中添加这种导航属性吗?

请您参考如下方法:

为了使关系可选,您需要在 TruckPart 实体中有一个可空 外键属性(加上与 HasOptional 的映射):

public int? PartId { get; set; }