C# 实体框架将用户添加到角色
我早些时候问了一个问题,这个问题是 基本上,我需要两个课程:C# 实体框架将用户添加到角色,c#,entity-framework,C#,Entity Framework,我早些时候问了一个问题,这个问题是 基本上,我需要两个课程: 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 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();
}
}
公共类用户:IUser
{
公共字符串Id{get;set;}
//简明扼要
公共IList角色{get;set;}
公共用户()
{
this.Id=Guid.NewGuid().ToString();
}
}
公共类角色:IRole
{
公共字符串Id{get;set;}
公共字符串名称{get;set;}
公共角色()
{
this.Id=Guid.NewGuid().ToString();
}
}
在myDbContext中,我有以下声明:
modelBuilder.Entity<User>()
.HasMany(m => m.Roles)
.WithMany()
.Map(m => {
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UserRoles");
});
modelBuilder.Entity()
.HasMany(m=>m.Roles)
.有很多
.Map(m=>{
m、 MapLeftKey(“用户ID”);
m、 MapRightKey(“RoleId”);
m、 ToTable(“用户角色”);
});
这一切都很完美。现在,我想向特定角色添加一个用户,因此我按照我的服务/存储库/工作单元设计模式创建了一个服务,如下所示:
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>();
}
}
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");
});
}
}
公共类UserRoleService:服务
{
公共用户角色服务(IUnitOfWork unitOfWork)
:基础(工作单元)
{
}
公共异步任务GetAllAsync(字符串用户ID,参数字符串[]包括)
{
return wait this.Repository.GetAll(includes).Where(m=>m.UserId.Equals(UserId,StringComparison.OrdinalIgnoreCase)).toListSync();
}
公共异步任务CreateAsync(用户角色模型)
{
var isInRole=wait isInRole(model.UserId,model.RoleId);
如果(isInRole)
抛出新的InvalidOperationException(string.Format(CultureInfo.CurrentCulture,Resources.UserInRole,新对象[]{model.RoleId}));
this.Repository.Create(model);
}
公共异步任务RemoveAsync(用户角色模型)
{
var isInRole=wait isInRole(model.UserId,model.RoleId);
如果(!isInRole)
抛出新的InvalidOperationException(string.Format(CultureInfo.CurrentCulture,Resources.UserNotInRole,新对象[]{model.RoleId}));
this.Repository.Remove(model);
}
公共异步任务IsInRole(字符串用户ID、字符串角色ID)
{
if(string.IsNullOrEmpty(userId))
抛出新的ArgumentNullException(“userId”);
if(string.IsNullOrEmpty(userId))
抛出新的ArgumentNullException(“roleId”);
var roles=wait this.GetAllAsync(userId);
var match=roles.Where(m=>m.RoleId.Equals(RoleId,StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
返回(匹配==null);
}
}
继承的服务类如下所示:
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>();
}
}
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");
});
}
}
公共类服务,其中T:class
{
私有只读存储库;
受保护的IRepository存储库
{
获取{返回this.repository;}
}
公共服务(IUnitOfWork unitOfWork)
{
如果(unitOfWork==null)
抛出新的ArgumentNullException(“unitOfWork”);
this.repository=unitOfWork.GetRepository();
}
}
现在,因为我的DbContext没有针对UserRoles的DbSet,所以我添加了一个。然后我接到一个投诉,说新表没有设置主键,所以我添加了一个。现在,我的DbContext如下所示:
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>();
}
}
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");
});
}
}
公共类数据库上下文:DbContext
{
//为简洁起见,请删除
公共数据库集角色{get;set;}
公共数据库集用户{get;set;}
公共数据库集用户角色{get;set;}
静态数据库上下文()
{
//Database.SetInitializer(null);//退出数据库,不执行任何操作(注释掉以创建数据库)
}
公共数据库上下文()
:base(“默认连接”)
{
base.Configuration.LazyLoadingEnabled=false;//禁用延迟加载
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove();//删除级联删除
//不简洁
modelBuilder.Entity().HasKey(m=>new{m.UserId,m.RoleId});
modelBuilder.Entity()
.HasMany(m=>m.Roles)
.有很多
.Map(m=>{
m、 MapLeftKey(“用户ID”);
m、 MapRightKey(“RoleId”);
m、 ToTable(“用户角色”);
});
}
}
现在的问题是,我的代码为UserRole创建了两个表,分别称为UserRoles和UserRoles1。
有人能告诉我如何让它只使用一个表吗?如果UserRole表示纯映射(即,它只包含UserId和RoleId,没有其他属性),那么实际上不需要UserRole对象。在DbContext中定义关系就足够了(您已经这样做了)。要将特定角色与特定用户关联,您只需执行以下操作:
user.Roles.Add(role);
…并提交数据库集
实体框架足够智能,可以为您维护多对多映射表,而不需要实际拥有表示映射本身的实体
注意:您尝试添加的角色对象需要是数据库上下文中的实体。如果您尝试创建角色实体,然后分配,EF将尝试插入(可能由于主键冲突而失败)。如果UserRole表示纯映射(即,它只包含UserId和RoleId,不包含其他属性),则实际上不需要UserRole对象。在DbContext中定义关系就足够了(您已经这样做了)。要将特定角色与特定用户关联,您只需执行以下操作:
user.Roles.Add(role);
…并提交数据库集
实体框架足够智能,可以为您维护多对多映射表,而不需要实际拥有表示映射本身的实体
注意:您尝试添加的角色对象需要是数据库上下文中的实体。如果您尝试创建角色实体,然后分配,EF将尝试插入(可能由于主键冲突而失败)。您使用过成员资格吗?您的用户有角色,但您的角色有