我目前正在试验EF,我有一些我无法解决的问题。
我有多到多关系的用户和角色实体。当我尝试用初始数据为数据库添加种子时,问题就出现了。两个用户和两个角色(在下面的teh代码中)是成功的种子。我可以在角色和用户表中看到条目。但是连接表只有一个带有user1 id和role1 id的条目。当我试图从db获得两个角色的用户时,它只有一个角色-- 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);
}
}发布于 2016-08-08 19:13:12
好吧,我想我找到了我的问题。似乎我的比较者在哪里的原因。我用泛型列表代替了SortedSet<>,一切都像预期的那样开始工作了。
下面是我的一个比较器的代码:
public class RoleComparer : IComparer<AppRole>
{
public int Compare(AppRole x, AppRole y)
{
return x.Id.CompareTo(y.Id);
}
}我还是不太明白它为什么会引起我的问题,所以如果有人知道,请告诉我。
https://stackoverflow.com/questions/38819195
复制相似问题