Entity Framework one to optional foreign key code first fluent mapping

c# ef-code-first entity-framework-6 mapping

Question

Tables

    User
    ------
    UserId   PK


    Access
    -------
    AccessId  PK
    UserId    FK to User.UserId

User Entity

public int Id { get; set; } 
public virtual Access Access { get; set; }

Access Entity

public int Id { get; set; } 
public int UserId { get; set; } 
public virtual User User { get; set; }

Access Mapping

...  
HasKey(t => t.Id);
Property(t => t.Id).HasColumnName("AccessId");
HasRequired(t => t.User).WithOptional(t => t.Access);
...

User Mapping

...
HasKey(t => t.Id);
Property(t => t.Id).HasColumnName("UserId");
...

Query

var access = _unitOfWork.Users.Get()
                .Where(u => u.Id == userId)
                .Select(u => u.Access)
                .FirstOrDefault();

Generated SQL

LEFT OUTER JOIN [dbo].[Access] AS [Extent2] 
   ON [Extent1].[UserId] = [Extent2].[AccessId] <-- ** PROBLEM IS HERE **

My query is attempting to join on the wrong column, even though I have PK/FK set up in the database and PKs specified on my entity maps. Can anyone spot what I'm missing? Thanks.

1
0
4/16/2014 4:08:13 PM

Accepted Answer

When mapping a 1..0 or 1 relationship in EF, the dependent relationship is expected to have its primary key be the foreign key of the principal.

In your case, this means that your Access entity should drop the AccessId primary key and make the UserId be your key.

If you can't change your schema to allow this, your best bet for a workaround will have to be making the relationship a 1..many and fudging it in your code.

4
4/16/2014 4:50:10 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow