I am using Entity Framwork DbContexts with a legacy database. I have 2 different properties of an entity that both need to reference the same lookup table, like so:
public class Address
{
public virtual AddressType AnAddressType {get; set;}
public virtual AddressType AnotherAddressType {get; set;}
}
// now here's a LINQ query that just flat won't work:
from a in Addresses select a;
The exception indicates that we tried to include a completely fictional field in the select list — the field doesn’t appear in my POCO or the table — it looks like it was expected by convention, it’s named AnAddressType_AddressType or something close to that
The AddressType entity does not have a corresponding navigation property on it. I cannot seem to get this to work. When I attempt to select data with my LINQ query, I get runtime errors.
Edit
I have other relations that are working (this code is generated from the “stock” DbContext generator). The thing about this one relation that is different is that the lookup table does not have a navigation property back to the main table (the lookup table is used all over the place, so I don’t really want to add nav properties from it to everything that uses it). EF seems to be having a problem with that. It’s probably a configuration vs. convention thing, and I have inadvertently tripped on some kind of convention problem.
You have a foreign key column name in your legacy database which doesn’t follow the EF conventions, for example: The foreign key column in your
Addressestable to theAddressTypestable for theAnAddressTyperelationship has the nameMyCrazyAnAddressTypeNumberCodeKeyId.But EF will assume by convention that the FK column name is:
[Nav.property]_[KeyColumn]. For example: IfAddressTypehas a PK with nameAddressTypeIdEF will assume the FK column has the nameAnAddressType_AddressTypeId. Because this doesn’t match you get the exception you describe. You must specify the FK column name explicitely to fix this problem:(code snippet partially stolen from Ladislav’s answer for convenience)
That’s my hypothesis.
Edit
Alternatively you can introduce a foreign key property into your model and tell EF by data annotations that this property is a FK to the corresponding navigation property: