Reputation: 53388
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.
Upvotes: 0
Views: 1660
Reputation: 5290
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.
Upvotes: 4