I\'ve narrowed this down to some issue between Code First and Database first EF, but I\'m not sure how to fix it. I\'ll try to be as clear as I can, but I honestly am missin
For me cause of this behavior was because of issue with defined mapping with Fluent API. I had 2 related types, where type A had optional type B object, and type B had many A objects.
public class A
{
…
public int? BId {get; set;}
public B NavigationToBProperty {get; set;}
}
public class B
{
…
public List ListOfAProperty {get; set;}
}
I had defined mapping with fluent api like this:
A.HasOptional(p=> p.NavigationToBProperty).WithMany().HasForeignKey(key => key.BId);
But the problem was, that type B had navigation property List
, so as a result I had SQLException Invalid column name A_Id
I attached Visual Studio Debug to EF DatabaseContext.Database.Log to output generated SQL to VS Output->Debug window
db.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
And generated SQL had 2 relations from B table -> one with correct id and other with the A_Id
The issue for the problem was, that I did not add this B.List
navigation property into mapping.
So this is how in my case correct mapping had to be:
A.HasOptional(p=> p.NavigationToBProperty).WithMany(x => x.ListOfAProperty).HasForeignKey(key => key.BId);