I've got multiple classes (including TPT) in my project. Each POCO has a BaseClass
, which has a GUID
(called GlobalKey
) as primary key.
First I used DataAnnotations
to create correct foreign keys. But then I've got problems synchronizing the corresponding GUID with the object itself.
Now I want to have only one virtual navigation property so that the GUID field in the database is created by NamingConvention
. But the field name always adds an underscore followed by the word GlobalKey
(which is right). When I want to remove the underscore, I don't want to go thru all my POCOs in the fluent API to do this:
// Remove underscore from Navigation-Field
modelBuilder.Entity<Person>()
.HasOptional(x => x.Address)
.WithMany()
.Map(a => a.MapKey("AddressGlobalKey"));
Any ideas to do this for all POCOS by overwriting a convention?
Thanks in advance.
Andreas
I found that key column customizations were not being caught by the ForeignKeyNamingConvention. Made this change to catch them.
I had issues when combining it with an id naming convention of EntityNameId.
When using the following convention to ensure the Customer table has CustomerId rather than simply Id.
The foreign key naming convention needs to be changed to the following.
I know this is a bit old, but here is a sample how I specify mapping columns through my fluent config (OnModelCreating):
Hope this helps,
I finally found an answer for this, by writing a custom convention. This convention works in EF 6.0 RC1 (code from last week), so I think it's likely to continue to work after EF 6.0 is released.
With this approach, the standard EF conventions identify the independent associations (IAs), and then create the EdmProperty for the foreign key field. Then this convention comes along and renames the foreign key fields.
Note that the Convention is added to your
DbContext
in yourDbContext.OnModelCreating
override, using:I have also seen the same problem when the type of the field is off. Double check the type of the field Ex:
pointing to a domain object with int as the State.Id type. Make sure that your types are same.
Most of these answers have to do with Independent Assocations (where the "MyOtherTable" navigation property is defined, but not the "int MyOtherTableId") instead of Foreign Key Assocations (where both are defined).
That is fine since the question is about IA (it uses MapKey), but I came across this question when searching for a solution to the same problem with FKAs. Since other people may come here for the same reason, I thought I would share my solution that uses a ForeignKeyDiscoveryConvention.
https://stackoverflow.com/a/43809004/799936