2014-10-02 60 views
0

目前,我有一个自定义用户。更新用户外键MVC 5

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; 
     } 
    } 

Company类

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; } 
} 

我想,使其指向时,该公司创建公司更新用户类;但是,更新不会保存。这里是我试图在数据库中保存引用的控制器部分。 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定期数据类型的关系?

回答

0

尝试将virtual添加到您的导航属性中,例如, public virtual Company Companypublic virtual ICollection...。如果没有他们,那么EF不能自动跟踪和/或保留它们。

docs

对于变化跟踪代理: 每个属性被映射到在数据模型必须有非密封的实体类型的属性(NotOverridable在Visual Basic),公共和虚拟(Visual Basic中的Overridable)获取和设置访问器。