一对一关系首先在ef代码中分配创建的对象

时间:2016-03-23 07:57:36

标签: .net entity-framework ef-code-first

我有两个像这样的实体

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

当然它会看到新对象并在数据库中创建新公司。如何将现有公司分配给新用户?

0 个答案:

没有答案