问题
Some of the entities in my application have 4 audit properties on them:
public virtual DateTime WhenAdded { get; set; }
public virtual DateTime? WhenUpdated { get; set; }
public virtual User AddedBy { get; set; }
public virtual User UpdatedBy { get; set; }
I am using a code first approach and have the following extension method to map the user properties:
public static void MapAuditFields<T>(this EntityTypeConfiguration<T> configuration) where T : class, IAuditable
{
configuration.HasOptional<User>(e => e.AddedBy)
.WithOptionalDependent()
.Map(a => a.MapKey("AddedByUserId"));
configuration.HasOptional<User>(e => e.UpdatedBy)
.WithOptionalDependent()
.Map(a => a.MapKey("UpdatedByUserId"));
}
This is working fine in most cases, but not on the User class, which of course has a recursive relationship with itself. I have seen various posts on the internet suggesting that entity framework has a bug when you try to customise join table column names in this scenario, for example:
Self-referencing many-to-many recursive relationship code first Entity Framework
and
http://social.msdn.microsoft.com/Forums/en-US/f058097d-a0e7-4393-98ef-3b13ab5b165d/code-first-sequence-contains-more-than-one-matching-element-exception-when-generating-schema?forum=adonetefx
The error I am getting is "Sequence contains more than one matching element".
Does anyone know if this has been fixed in entity framework 6?
Many thanks.
回答1:
Use WithMany()
instead of WithOptionalDependent()
as a user can add or update multiple other users
Class:
public class User
{
public int Id { get; set; }
public virtual User AddedBy { get; set; }
public virtual User UpdatedBy { get; set; }
}
Fluent API calls:
modelBuilder.Entity<User>()
.HasOptional( u => u.AddedBy )
.WithMany()
.Map( fkamc => fkamc.MapKey( "AddedByUserId" ) );
modelBuilder.Entity<User>()
.HasOptional( u => u.UpdatedBy )
.WithMany()
.Map( fkamc => fkamc.MapKey( "UpdatedByUserId" ) );
Results:

来源:https://stackoverflow.com/questions/21878457/can-you-customise-foreign-key-names-in-self-referencing-entities-in-entity-frame