【问题标题】:EF 6.x: Can't seed tables with many-to-many relationshipEF 6.x:不能播种具有多对多关系的表
【发布时间】:2016-08-07 22:39:11
【问题描述】:

我目前正在尝试使用 EF,但我遇到了以下我无法解决的问题。

我有具有多对多关系的用户和角色实体。当我尝试使用初始数据为数据库播种时出现问题。成功播种了两个用户和两个角色(在下面的代码中)。我可以在角色和用户表中看到条目。但是联结表只有一个带有user1 idrole1 id 的条目。当我试图从 db 中获取具有 2 个角色的用户时,它只有一个角色 - role1。 我不知道为什么。我的错误在哪里,我该如何正确地做到这一点?这是我的代码:

实体

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

用户

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

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

角色

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

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
    }
}

种子代码

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);
    }
}

【问题讨论】:

    标签: c# .net entity-framework many-to-many code-first


    【解决方案1】:

    好的,我想我找到了我的问题。看来我的Comparers是哪里的原因。 我用通用列表替换了SortedSet&lt;&gt;,一切都开始按预期工作了。

    这是我的一个比较器的代码:

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

    我仍然不太明白为什么它会导致我的问题,所以如果有人知道,请告诉我。

    【讨论】:

      猜你喜欢
      • 2022-10-17
      • 2013-05-02
      • 2020-10-08
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      相关资源
      最近更新 更多