具有null外键的EF Navigation Property

时间:2021-06-20 11:49:46

I'm attempting to use navigation properties for the first time in lieu of doing joins. I cannot get a situation to work where it would normally be done with a left outer join. In the following example, I'm only getting results back where the foreign key is non-null. I need all results back. What am I missing?

我试图第一次使用导航属性而不是连接。我通常无法通过左外连接来完成工作。在下面的示例中,我只返回外键为非null的结果。我需要回复所有结果。我错过了什么?

public class User
{
    [Key]
    public int UserID {get;set;}

    public String Name {get;set;}
}

public class Shipment
{
    [Key]
    public int ShipmentID {get;set;}

    public int? SignedForByID {get;set;}

    [ForeignKey("SignedForByID")]
    public virtual User SignedForBy{get;set;}
}

navigation property mapping:

导航属性映射:

 Shipment.HasOptional(x=> x.SignedForBy).WithMany()
.HasForeignKey(y=> y.SignedForByID).WillCascadeOnDelete(false);

query:

查询:

var data = (from s in context.Set<Shipment>()
            select new {
                    ShipmentID = s.ShipmentID,
                    SignedForBy = s.SignedForBy
                        });

1 个解决方案

#1


1  

The problem was not shown in this example. The mappings are generated by a helper class. In some cases, the helper class incorrectly mapped the navigation properties with the .HasRequired() method instead of the .HasOptional(). Correcting the mapping class has fixed the issue.

此示例中未显示该问题。映射由辅助类生成。在某些情况下,助手类使用.HasRequired()方法而不是.HasOptional()错误地映射导航属性。更正映射类已修复此问题。

#1


1  

The problem was not shown in this example. The mappings are generated by a helper class. In some cases, the helper class incorrectly mapped the navigation properties with the .HasRequired() method instead of the .HasOptional(). Correcting the mapping class has fixed the issue.

此示例中未显示该问题。映射由辅助类生成。在某些情况下,助手类使用.HasRequired()方法而不是.HasOptional()错误地映射导航属性。更正映射类已修复此问题。