简体   繁体   English

EF 6.x:无法对具有多对多关系的表进行种子处理

[英]EF 6.x: Can't seed tables with many-to-many relationship

I'm currently experimenting with EF and I have following problem which I can't solve. 我正在尝试使用EF,我遇到了以下无法解决的问题。

I have User and Role entities with many-to-many relationship. 我有具有多对多关系的用户和角色实体。 The problem appears when I'm trying to seed database with initial data. 当我尝试使用初始数据为数据库设定种子时,会出现问题。 Two users and two roles(in teh code below) are seeded successfully. 两个用户和两个角色(在下面的代码中)成功播种。 I can see entries in Roles and Users tables. 我可以在Roles和Users表中看到条目。 But junction table has only one entry with user1 id and with role1 id . 但是联结表只有一个带有user1 idrole1 id条目。 When I'm trying to get user with 2 roles from db, It has only one role - role1 . 当我试图从db获得2个角色的用户时,它只有一个角色 - role1 And I don't know why. 我不知道为什么。 Where is my mistake and how can I do this correctly? 我的错误在哪里,我该如何正确地做到这一点? Here's my code: 这是我的代码:

Entity 实体

public abstract class Entity
{
    public int Id { get; set; }
}

User 用户

public class AppUser : Entity
{
    ...
    public virtual ICollection<AppRole> Roles { get; set; }

    public AppUser()
    {
        Roles = new SortedSet<AppRole>(new RoleComparer());
    }
}

Role 角色

public class AppRole : Entity
{
    public RoleEnum Role { get; set; } 
    public ICollection<AppUser> Users { get; set; }
    public AppRole()
    {
        Users = new SortedSet<AppUser>(new UserComparer());
    }
}

FluentAPI FluentAPI

public class UserMap : EntityTypeConfiguration<AppUser>
{
    public UserMap()
    {
        ToTable("Users");
        ...
        #region Many-to-Many
        HasMany(usr => usr.Roles)
                .WithMany(r => r.Users)
                .Map(map =>
                {
                    map.ToTable("UsersAndRoles");
                    map.MapLeftKey("AppUserId");
                    map.MapRightKey("AppRoleId");
                });
        #endregion
    }
}

Seed code 种子代码

public class DropCreateTestDbAlways : DropCreateDatabaseAlways<UnitTestContext>
{
    protected override void Seed(UnitTestContext context)
    {
        var role1 = new AppRole();
        var role2 = new AppRole() { Role = RoleEnum.Administrator };
        context.Roles.Add(role1);
        context.Roles.Add(role2);

        var user1 = new AppUser()
        {
            UserName = "RegularUser",
            Email = "regular@email.com",
            PasswordHash = "FGJSDBXNLSNLSDDSJSCLNCS",
            UserProfile = new AppUserProfile()
        };
        var user2 = new AppUser()
        {
            UserName = "AdminUser",
            Email = "admins@email.com",
            PasswordHash = "FGJSDBXNLSNLSDDSJSCLNCS",
            UserProfile = new AppUserProfile()
        };

        user1.Roles.Add(role1);
        user2.Roles.Add(role1);
        user2.Roles.Add(role2);

        context.Users.Add(user1);
        context.Users.Add(user2);
        base.Seed(context);
    }
}

Ok, I think I've found my problem. 好吧,我想我已经找到了问题。 It seems that my Comparers where the cause. 看来我的比较器所在的原因。 I replaced SortedSet<> with generic List, and everything started working as expected. 我将SortedSet<>替换为通用List,一切都按预期开始工作。

Here is the code of one of my comparers: 这是我的一个比较器的代码:

public class RoleComparer : IComparer<AppRole>
{
    public int Compare(AppRole x, AppRole y)
    {
        return x.Id.CompareTo(y.Id);
    }
}

I still can't quite understand why it was causing my problems, so if someone knows, please, tell me. 我仍然不太明白为什么它会导致我的问题,所以如果有人知道,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM