【问题标题】:Update User Foreign Key MVC 5更新用户外键 MVC 5
【发布时间】:2014-10-02 12:50:28
【问题描述】:

目前,我有一个自定义用户。

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public ApplicationUser()
{
this.Applicants = new List<Applicant>();
}

public Nullable<DateTime> Expiration { get; set; }
public int Active { get; set; }

        public Company Company { get; set; }
        public Department Department { get; set; }

        public ICollection<Applicant> Applicants { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // Add custom user claims here
            return userIdentity;
        }
    }

公司类

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Department> Departments { get; set; }
    public ICollection<ApplicationUser> Users { get; set; }
}

我想更新 User 类,使其在创建公司时指向公司;但是,更新不会保存。这是我试图将引用保存在数据库中的控制器部分。 ApplicationUser 应该指向数据库中公司的 ID。

// _db is for my Identity context
int id = Convert.ToInt32(User.Identity.GetUserId());
ApplicationUser user = UserManager.FindById(id);
Company company = new Company
{
    Name = model.Name
};
_db.Companies.Add(company);
_db.SaveChanges();
user.Company = company;
UserManager.Update(user);

那么对于用户与对象之间的关系而不是字符串或 int 等常规数据类型之间的关系,我做错了什么或误解了?

【问题讨论】:

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


    【解决方案1】:

    尝试将virtual 添加到您的导航属性中,例如public virtual Company Companypublic virtual ICollection...。如果它们不是 virtual,EF 将无法自动跟踪和/或持久化它们。

    根据docs

    对于更改跟踪代理: 映射到数据模型中实体类型的属性的每个属性都必须具有非密封(Visual Basic 中的 NotOverridable)、公共和虚拟(Visual Basic 中的可替代)get 和 set 访问器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多