我正在尝试在ef核心中插入多对多关系实体。
尝试插入时出现此错误:
Object reference not set to an instance of an object
这是实体:
public class ApplicationUser : IdentityUser
{
... other properties
//many to many
public ICollection<UserPermission> UserPermissions { get; set; }
}
public class Permission:EntityBase
{
public string Name { get; set; }
//many to many
public ICollection<UserPermission> UserPermissions { get; set; }
}
//join entity
public class UserPermission
{
public string UserId { get; set; }
public ApplicationUser User { get; set; }
public int PermissionId { get; set; }
public Permission Permission { get; set; }
}
这里也是Fluent-Api
//user-permission many to many relationship
builder.Entity<UserPermission>()
.HasKey(up => new { up.UserId, up.PermissionId });
builder.Entity<UserPermission>()
.HasOne(up => up.User)
.WithMany(p => p.UserPermissions)
.HasForeignKey(x => x.UserId);
builder.Entity<UserPermission>()
.HasOne(p => p.Permission)
.WithMany(u => u.UserPermissions)
.HasForeignKey(x => x.PermissionId);
我在这里尝试了一种插入方法:
public void AssignPermissions(ApplicationUser user,ICollection<int> permissions){
try
{
if (user != null)
{
foreach (var per in permissions)
{
var permission = _permissionRepository.GetById(per);
var userPermission = new UserPermission {
UserId = user.Id,
PermissionId = permission.Id
};
userPermission.Permission = permission;
userPermission.User = user;
user.UserPermissions.Add(userPermission);
_uow.Commit();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
当我尝试在AssignPermissions方法中分配权限时,出现错误。
我该如何解决?
谢谢
答案 0 :(得分:-1)
我通过在Include
查询中添加ApplicationUser
参数来解决。
var user = await _userManager.Users
.Include(x => x.UserPermissions)
.SingleAsync(x => x.Email == model.Email);