Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Navigation Property with null foreign key

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?

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
                        });
like image 402
Sam Avatar asked Sep 04 '15 13:09

Sam


1 Answers

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.

like image 126
Sam Avatar answered Nov 16 '22 02:11

Sam