[翻译]  EF Navigation Property with null foreign key

[CHINESE]  具有null外键的EF Navigation Property


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()错误地映射导航属性。更正映射类已修复此问题。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号