Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET MVC 5实体框架-关系_C#_Asp.net_Asp.net Mvc_Entity Framework - Fatal编程技术网

C# ASP.NET MVC 5实体框架-关系

C# ASP.NET MVC 5实体框架-关系,c#,asp.net,asp.net-mvc,entity-framework,C#,Asp.net,Asp.net Mvc,Entity Framework,我目前正在开发一个web应用程序。我正在使用身份验证和我的用户角色 我希望我的应用程序中的每个用户都有一个关联的“机构”。该机构包含名称和描述。这是我的IdentityUser类: public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser&

我目前正在开发一个web应用程序。我正在使用身份验证和我的用户角色

我希望我的应用程序中的每个用户都有一个关联的“机构”。该机构包含名称和描述。这是我的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; }
    }
公共类应用程序用户:IdentityUser
{
公共异步任务GenerateUserIdentityAsync(用户管理器)
{
//注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
var userIdentity=wait manager.CreateIdentityAsync(这是DefaultAuthenticationTypes.ApplicationOkie);
//在此处添加自定义用户声明
返回用户身份;
}
[显示(名称=“机构”)]
公共机构{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");
}
if(!context.Users.Any(u=>u.UserName==“mxfragz”))
{
var rolemanger=new rolemanger(new RoleStore(new identiesdb());
roleManager.Create(新的IdentityRole(“管理员”));
var store=新用户存储(上下文);
var-manager=新用户管理器(存储);
var user=newapplicationuser{UserName=“mxfragz”};
user.Institution=new Institution(){Name=“London”,Description=“Description”};
创建(用户,“密码”);
manager.AddToRole(user.Id,“admin”);
}
我的问题是,当我在我的web应用程序中创建新用户时,我找不到一种方法来关联现有机构(这里只创建了“伦敦”)。 根据我到目前为止所做的工作,当我创建一个用户时,我会获取所选机构的ID并找到一个现有机构,以便将其与我的用户中定义的机构属性相关联。当我这样做时,entity framework将创建一个新机构,并将其与我的用户关联,而不是关联已找到的现有机构。我最终得到了两个不同的机构,它们的名称和描述都相同。这是我的密码:

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);
}
公共异步任务创建(RegisterViewModel模型) { if(ModelState.IsValid) { var user=new ApplicationUser(){UserName=model.UserName,Email=string.Empty}; int selected=int.Parse(model.SelectedInstitution); user.Institutions=new InstitutionsDb().Institutions.Where(x=>x.Id==selected.First(); IdentityResult result=await UserManager.CreateAsync(用户、模型、密码); if(result.successed) { var rolemanger=new rolemanger(new RoleStore(new identiesdb()); UserManager.AddToRole(user.Id.ToString(),roleManager.Roles.Where(x=>x.Id==model.SelectedRole.ToString()).First().Name); 返回重定向操作(“索引”、“用户”); } 其他的 { 加法器(结果); } } model.Roles=GetRoles(); model.Institutions=GetInstitutions(); 返回视图(模型); } 我找到了几个关于使用Attach方法的主题,但即使我尝试使用它,它也不起作用。
我做错什么了吗?或者有什么方法可以实现我想做的吗?

需要通过机构上的虚拟集合以及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; }
}

这应该允许您在从
UserManager

检索
ApplicationUser
时调用
user.Institution.Name
,不要设置
user.Institution
,还要在您的模型中公开外键(
user.InstitutionId
),并设置其值。我刚刚尝试了它,它工作了!但是,有没有一种方法可以直接关联实体而不仅仅是ID?因为使用此解决方案,我无法从用户(
User.Institution.Name
)实际访问机构。除非您可以先将
机构
附加到
用户管理器
,但我不知道这是否可行(我不太了解此用户管理器)。另一种方法是以另一种方式执行,并将
ApplicationUser
对象添加到所附
机构的
ApplicationUsers
集合(如果存在)中。
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);
}