我使用带有owin Identity 2.1的web api 2.2和实体框架6.1.2一切正常,除非我试图删除或添加角色给用户,我收到以下错误消息:< / p>
操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。
if (!await _userManager.IsInRoleAsync(user.Id, role.Name))
//Excption is thrown here with the above message
await _userManager.AddToRoleAsync(user.Id, role.Name);
更新1
用于DbContext
public class EFDbContext : IdentityDbContext<ApplicationUser>
{
public EFDbContext()
: base("name=AppConnectionString", throwIfV1Schema: false)
{
this.Configuration.LazyLoadingEnabled = false;
}
public static EFDbContext Create()
{
return new EFDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
Parallel.ForEach(typesToRegister, type =>
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
});
base.OnModelCreating(modelBuilder);
}
public virtual TEntity AttachEntityToContext<TEntity>(TEntity entity) where TEntity : BaseEntity
{
var alreadyAttached = Set<TEntity>().Local.FirstOrDefault(x => x.Id == entity.Id);
if (alreadyAttached == null)
{
Set<TEntity>().Attach(entity);
return entity;
}
else
return alreadyAttached;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
{
return base.Set<TEntity>();
}
}
}