0
自定義Identity用戶對象包含列表對象區域和代碼一樣。當用戶註冊時,他可以請求他可以工作的區域以及他的角色是什麼。一旦用戶註冊電子郵件到管理員審覈用戶並批准註冊請求。直到管理員批准的用戶被鎖定。如有必要,Amin可以修改用戶區域選擇和請求角色。所以問題就在這裏。我如何更新應用程序用戶及其地區和角色?我在下面嘗試,但它給了我一個例外。我是否需要先更新應用程序的用戶,然後檢索它並添加區和角色進行發送更新?(許多DB調用)EF update ApplicationUser(從IdentityUser繼承)與多對多關係集合
上型酒店'地區「ApplicationUser」不是一個原始的或複雜的財產。 Property方法只能用於原始或複雜屬性。使用參考或收集方法。)
ApplicationUser
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
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;'以便保留堆棧跟蹤。 – pinkfloydx33