[英]ASP.NET MVC 5 Entity Framework - Relations
我目前正在開發一個Web應用程序。 我正在使用Identity進行身份驗證和用戶角色。
我希望我的應用程序中的每個用戶都有一個關聯的“機構”。 該機構包含名稱和描述。 這是我的IdentityUser類:
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;
}
[Display(Name="Institution")]
public Institution Institution { get; set; }
}
當我更新我的數據庫時,執行Seed方法,這個,我正在創建一個具有“admin”角色的用戶,並且我關聯了一個機構。 這是我的種子方法:
if (!context.Users.Any(u => u.UserName == "mxfragz"))
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new IdentitiesDb()));
roleManager.Create(new IdentityRole("admin"));
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser { UserName = "mxfragz" };
user.Institution = new Institution() { Name = "London", Description="Description" };
manager.Create(user, "password");
manager.AddToRole(user.Id, "admin");
}
我的問題是,當我在我的Web應用程序中創建一個新用戶時,我找不到關聯現有機構的方法(這里只創建了“倫敦”)。 根據我到目前為止所做的工作,當我創建用戶時,我獲取所選機構的ID並找到現有機構,以便將其與我的用戶中定義的Institution屬性相關聯。 當我這樣做時,實體框架不是關聯已找到的現有機構,而是創建一個新機構,並將其關聯到我的用戶。 我最終得到了兩個具有相同名稱和描述的不同機構。 這是我的代碼:
public async Task<ActionResult> Create(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.Username, Email = string.Empty };
int selected = int.Parse(model.SelectedInstitution);
user.Institution = new InstitutionsDb().Institutions.Where(x => x.Id == selected).First();
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new IdentitiesDb()));
UserManager.AddToRole(user.Id.ToString(), roleManager.Roles.Where(x => x.Id == model.SelectedRole.ToString()).First().Name);
return RedirectToAction("Index", "Users");
}
else
{
AddErrors(result);
}
}
model.Roles = GetRoles();
model.Institutions = GetInstitutions();
return View(model);
}
我發現了幾個關於使用Attach方法的主題,但即使我嘗試使用它,它也無效。 難道我做錯了什么 ? 或者有什么方法可以做我想做的事情?
外鍵關系需要通過Institution上的虛擬集合以及ApplicationUser上的實際外鍵值進行公開。
public class ApplicationUser : IdentityUser
{
//...
public int InstitutionId { get; set; }
[Display(Name="Institution")]
[ForeignKey("InstitutionId")] //This attribute isn't strictly necessary but adds clarity
public Institution Institution { get; set; }
}
public class Institution
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
}
EF將根據下面顯示的InstitutionId自動在虛擬財產上附加相關的機構。
我建議剛加入DbSet<Institutions>
的ApplicationDbContext
,而不是它自己的InstitutionsDb
背景下,這可能是你的問題的一部分,因為UserManager
勢必只對ApplicationDbContext
或曾經方面已配置詮釋他IdentityConfig.cs
文件。
public async Task<ActionResult> Create(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.Username, Email = string.Empty };
int selected = int.Parse(model.SelectedInstitution);
var context = HttpContext.GetOwinContext().Get<ApplicationDbContext>()
//Set the id
user.InstitutionId = context.Institutions.Where(x => x.Id == selected).First().Id;
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new IdentitiesDb()));
UserManager.AddToRole(user.Id.ToString(), roleManager.Roles.Where(x => x.Id == model.SelectedRole.ToString()).First().Name);
return RedirectToAction("Index", "Users");
}
else
{
AddErrors(result);
}
}
model.Roles = GetRoles();
model.Institutions = GetInstitutions();
return View(model);
}
這應該允許您從UserManager
檢索ApplicationUser
時調用user.Institution.Name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.