我之前问了一个问题answered here
基本上我需要2个课程:
public class User : IUser
{
public string Id { get; set; }
// Stripped for brevity
public IList<Role> Roles { get; set; }
public User()
{
this.Id = Guid.NewGuid().ToString();
}
}
public class Role : IRole
{
public string Id { get; set; }
public string Name { get; set; }
public Role()
{
this.Id = Guid.NewGuid().ToString();
}
}
在我的 DbContext 中,我有这个声明:
modelBuilder.Entity<User>()
.HasMany(m => m.Roles)
.WithMany()
.Map(m => {
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UserRoles");
});
一切都很完美。现在,我想将用户添加到特定角色,因此我按照我的服务/存储库/工作单元设计模式创建了一个服务:
public class UserRoleService : Service<UserRole>
{
public UserRoleService(IUnitOfWork unitOfWork)
: base(unitOfWork)
{
}
public async Task<IList<UserRole>> GetAllAsync(string userId, params string[] includes)
{
return await this.Repository.GetAll(includes).Where(m => m.UserId.Equals(userId, StringComparison.OrdinalIgnoreCase)).ToListAsync();
}
public async Task CreateAsync(UserRole model)
{
var isInRole = await IsInRole(model.UserId, model.RoleId);
if (isInRole)
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.UserInRole, new object[] { model.RoleId }));
this.Repository.Create(model);
}
public async Task RemoveAsync(UserRole model)
{
var isInRole = await IsInRole(model.UserId, model.RoleId);
if (!isInRole)
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.UserNotInRole, new object[] { model.RoleId }));
this.Repository.Remove(model);
}
public async Task<bool> IsInRole(string userId, string roleId)
{
if (string.IsNullOrEmpty(userId))
throw new ArgumentNullException("userId");
if (string.IsNullOrEmpty(userId))
throw new ArgumentNullException("roleId");
var roles = await this.GetAllAsync(userId);
var match = roles.Where(m => m.RoleId.Equals(roleId, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
return (match == null);
}
}
继承的服务类如下所示:
public class Service<T> where T : class
{
private readonly IRepository<T> repository;
protected IRepository<T> Repository
{
get { return this.repository; }
}
public Service(IUnitOfWork unitOfWork)
{
if (unitOfWork == null)
throw new ArgumentNullException("unitOfWork");
this.repository = unitOfWork.GetRepository<T>();
}
}
现在,因为我的 DbContext UserRoles 没有 DbSet ,所以会抱怨,所以我添加了一个。然后我抱怨新表没有设置主键,所以我添加了一个。所以现在我的 DbContext 看起来像这样:
public class DatabaseContext : DbContext
{
// Removed for brevity
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
static DatabaseContext()
{
//Database.SetInitializer<IdentityContext>(null); // Exsting database, do nothing (Comment out to create database)
}
public DatabaseContext()
: base("DefaultConnection")
{
base.Configuration.LazyLoadingEnabled = false; // Disable Lazy Loading
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); // Remove Cascading Delete
// Removed from brevity
modelBuilder.Entity<UserRole>().HasKey(m => new { m.UserId, m.RoleId });
modelBuilder.Entity<User>()
.HasMany(m => m.Roles)
.WithMany()
.Map(m => {
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UserRoles");
});
}
}
我现在遇到的问题是,我的代码为 UserRole 创建了两个名为 UserRoles 和 UserRoles1 的表。 有人可以告诉我如何只使用一张桌子吗?
答案 0 :(得分:4)
如果UserRole表示纯映射(即它只包含UserId和RoleId,而不包含其他属性),则实际上并不需要UserRole对象。在DbContext中定义关系就足够了(你已经完成了)。要将特定角色与特定用户相关联,您只需执行以下操作:
user.Roles.Add(role);
...并提交DbSet
实体框架非常智能,可以为您维护多对多映射表,而无需实际拥有代表映射本身的实体。
注意:您尝试添加的角色对象需要是数据库上下文中的实体。如果您尝试创建角色实体然后分配,EF将尝试插入(并且可能由于主键违规而失败)。