I have a C# (C# 7.5) application that is using EF6.
I have a table that contains two foreign keys. Both are one:one relationships and both are required.
When I load a record from the database, the required relationship is populated with the target record.
The issue is that the second relationship is always null, even though the field marked as a foreign key contains a valid value.
[Table("Bob")]
public class bob
{
[Key]
public Guid Id { get; set; }
public String Name { get; set; }
public Guid WorkingId { get; set; }
[ForeignKey("WorkingId")]
public virtual WorkingTable WorkingTable { get; set; }
public Guid NotWorkingId { get; set; }
//[ForeignKey("NotWorkingId") // commented out as causes exception
public virtual NotWorkingTable NotWorkingTable { get; set; }
}
[Table("WorkingTable")]
public class WorkingTable
{
[Key]
public Guid Id { get; set; }
public String AValue { get; set; }
}
[Table("NotWorkingTable")]
public class NotWorkingTable
{
[Key]
public Guid Id { get; set; }
public String AValue { get; set; }
}
Both relationships are defined in SQL Server as:
ForeignKeyBaseTable: Bob
ForeignKeyColumns: WorkingId (and NotWorkingId)
Primary/Unique Key Base: WorkingTable (and NotWorkingTable)
Primary/Unique Key Column: Id (for both)
The code that I am using inside of the DbContext is
var results = BobDbSet.AsNoTracking().ToList();
If I examine results[0] as an example, I can see that workingId and WorkingTable are populated, but while NotWorkingId has a valid value (resolves to the target in T-SQL), NotWorkingTable is null.
Note: I am using ASP.NET running on .NET 4.8 (not ASP.NET Core or EF Core).
Does anyone have an idea on how to diagnose this issue? As far as I am aware, adding the foreign key property onto the virtual class definition causes EF to try and match it with the first key defined in that class (in this case Id).
When I examine things with the debugger, I can see the EF RelationshipManager only has an entry for the first relationship and not the second.
//[ForeignKey("NotWorkingId") // commented out as causes exception(besides missing the trailing]) It will help to see the actual entities with the problem, trimmed down to just the navigation properties and FK definitions. Attempts to simplify an example often hides the actual problem.WorkingTableandNotWorkingTablehad a data annotation[key](with a lower-case "k") - this is incorrect and I fixed it in your code - it must be[Key]with an upper-case "K" - could that be the problem?