我有两个类:实体框架 - 代码先保存多对多关系
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public virtual ICollection<Company> Companies { get; set; }
}
在我的MVC应用程序控制器从后得到新的公司。我想将当前用户添加到创建的公司中。
User user = GetCurrentLoggedUser();
//company.Users = new ICollection<User>(); // Users is null :/
company.Users.Add(user); // NullReferenceException
companyRepository.InsertOrUpdate(company);
companyRepository.Save();
它应该看起来应该如何正常工作?我还不知道它,但添加用户到集合后,我希望保存到数据库的问题。任何有关它应该是什么样的提示将不胜感激。
在这一刻我看不到HashSet和Collection之间有很大的区别(我选择HashSet)。你帮助我理解如何管理我的上下文。在获取用户之前,我将CompanyRepository的上下文设置为UserRepository。这给我快速的工作解决方案。非常感谢。 – bizon 2011-03-22 23:08:36