【问题标题】:Add IdentityUser as property of other model将 IdentityUser 添加为其他模型的属性
【发布时间】:2017-09-13 18:30:32
【问题描述】:

我正在使用 MVC5 和 EntityFramework 6.1.3 使用 ASP.NET Identity。 我的问题是我无法将 IdentityUser 作为属性添加到另一个模型。

我的应用程序允许用户创建项目:

 public class Project
    {
        public int ProjectID { get; set; }
        public string ProjectName { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
    }

在创建新项目的操作方法中,我正在尝试像这样添加登录用户:

public ActionResult Create([Bind(Include = "ProjectID,ProjectName")] Project project)
        {
            if (ModelState.IsValid)
            {
                // I added the first two lines of code below. 
                var loggedInUser = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
                project.ApplicationUser = loggedInUser;
                db.Projects.Add(project);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(project);
        }

loggedInUser 设置正确,它获得所有正确的属性。但是,当我尝试保存更新的上下文时,出现以下错误:

"Validation failed for one or more entities. The validation errors are: User name hellogoodnight@gmail.com is already taken."

因此,出于某种原因,我的代码显然试图创建一个新用户,而不是将现有用户添加到创建的项目中。为什么? 这不是将 IdentityUser 作为导航属性添加到模型的方法吗?

【问题讨论】:

  • 两个通用的cmets,为什么不能把userid存储为类的属性,根据需要进行身份用户查找。似乎更节省资源。为什么你不能也让类从身份用户模型继承?我认为一般来说你的问题是它认为在保存新模型更改的过程中,它正试图保存一个副本,就像错误所说的那样。您需要解决只有一个任何身份用户的实体并引用它,而不是尝试重新保存重复数据。这正是身份的含义,唯一的一个。

标签: c# asp.net-mvc entity-framework asp.net-identity


【解决方案1】:

我想您有two 表,其中一对多 relationship

Project 实体只能附加一个useruser 实体可以有一个或多个projects

因此,您需要在 Project 类中附加外键,以便正确允许 Entity frameworkmap 关系并建立 relational 模型(数据库)和conceptual 模型之间的关联。

 public class Project
 {
    public int ProjectID { get; set; }
    public string ProjectName { get; set; }
    public int ApplicationUserId{ get; set;}
    public virtual ApplicationUser ApplicationUser { get; set; }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多