【发布时间】:2016-09-10 10:43:08
【问题描述】:
自定义身份用户对象包含与代码一样的列表对象区域。当用户注册时,他可以请求他可以在哪些区域工作以及他的角色是什么。用户注册电子邮件后,管理员将查看用户并批准注册请求。直到管理员批准的用户被锁定。 Amin 可以根据需要修改用户区域选择和请求角色。所以问题来了。如何更新应用程序用户及其区域和角色?我在下面尝试过,但它给了我一个例外。我是否需要先更新应用程序用户然后检索它并添加区域和角色进行发送更新?(许多数据库调用)
“ApplicationUser”类型的“Regions”属性不是原始或复杂属性。 Property 方法只能用于原始或复杂属性。使用引用或收集方法。)
应用程序用户
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
//Extended Properties
public DateTime? BirthDate { get; set; }
//Key Mappings
public virtual ICollection<Region> Regions { get; set; }
public virtual string DisplayName { get; set; }
public virtual string UserAccountApproverId { get; set; }
public virtual ApplicationUser UserAccountApprover { get; set; }
}
地区
public class Region:AuditableBase
{
public string RegionCode { get; set; }
public string Description { get; set; }
public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; }
}
更新 ApplicationUser 的代码 sn-p
public int ApproveNewUser(UserModel userModel)
{
try
{
ApplicationUser user = new ApplicationUser()
{
Id = userModel.Id,
UserName = userModel.EmailAddress,
LockoutEnabled = false
};
_ctx.Users.Attach(user);
var entry = _ctx.Entry(user);
entry.Property(e => e.LockoutEnabled).IsModified = true;
if (userModel.CheckedRegionsUpdated)
{
AddRegionsToUser(userModel.SelectedRegions, user);
entry.Property(e => e.Regions).IsModified = true;
}
return _ctx.SaveChanges();
}
catch (OptimisticConcurrencyException ex)
{
var objectContext = ((IObjectContextAdapter)_ctx).ObjectContext;
objectContext.Refresh(RefreshMode.ClientWins, _ctx.Users);
return _ctx.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
private void AddRegionsToUser(IList<Region> regionsToAdd, ApplicationUser appUser)
{
appUser.Regions = new List<Region>();
var regionsIds = regionsToAdd.Select(x => x.Id).ToArray<int>();
List<Region> regionssFromDb =
this._ctx.Regions.Where(rg => regionsIds.Contains(rg.Id)).ToList();
foreach (Region region in regionssFromDb)
{
appUser.Regions.Add(region);
}
}
【问题讨论】:
-
不是答案,只是一个注释。您应该删除
catch (Exception ex)块,因为这与不捕获异常相同,但会破坏堆栈跟踪。如果您必须捕获基本的Exception类型(例如用于记录目的或为了简洁而省略的内容),则将throw ex;更改为throw;以便保留堆栈跟踪。
标签: asp.net .net entity-framework asp.net-web-api entity-framework-6