我有两个像这样的实体
public class User : IdentityUser
{
public virtual Company RegisteredCompany { get; set; }
..
}
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
}
当我尝试使用创建的公司
创建新用户时using (var ctx = new AppContext())
{
var company = ctx.Companies.SingleOrDefault(c => c.Id == model.CompanyId);
...
var user = new User
{
UserName = model.Msisdn,
RegisteredCompany = company,
...
};
var result = await this.UserManager.CreateAsync(user, Helper.GetUniqueKey(30));
if (!result.Succeeded)
{
...
}
...
}
我得到这样的错误
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
如果我在这样的上下文中分离对象
var company = ctx.Companies.AsNoTracking().SingleOrDefault(c => c.Id == model.CompanyId);
当然它会看到新对象并在数据库中创建新公司。如何将现有公司分配给新用户?