Can you customise foreign key names in self referencing entities in entity framework?

假装没事ソ 提交于 2019-12-24 12:53:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!