0

首先,错误是“一个实体对象不能被多个IEntityChangeTracker实例引用”

我有两个实体 User 和 UsersInHospitals

这是我为用户创建新帐户的方法

var user = new User(); user.UserID = Guid.NewGuid(); user.Address = employmentAddress.Trim(); user.ZipCode = int.Parse(zipcode.Trim());

UsersInHospital hospitalAff;

          hospitalAff = new UsersInHospital()
           {
                    UserID = user.UserID,
                    HospitalID = Guid.Parse(hospitalAff1),
                    IsEmployed = Boolean.Parse(isEmployed1)
           };
           user.UsersInHospitals.Add(hospitalAff);

                hospitalAff = new UsersInHospital()
                {
                    UserID = user.UserID,
                    HospitalID = Guid.Parse(hospitalAff1),
                    IsEmployed = Boolean.Parse(isEmployed2)
                };
                user.UsersInHospitals.Add(hospitalAff);

并保存

_db.AddToUsers(user);
return _db.SaveChanges(); //THIS LINE GIVES ME ERROR

我正在使用实体框架 4。我怀疑我是否必须为每个医院实体单独创建变量

4

2 回答 2

0

您必须为医院的用户创建 2 个单独的变量,否则您会将同一对象的 2 个引用添加到列表中,这就是 Entity Framework 尝试将 IEntityChangeTracker 两次添加到同一对象的原因:

var user = new User
{
    UserID = Guid.NewGuid(), 
    Address = employmentAddress.Trim(), 
    ZipCode = int.Parse(zipcode.Trim())
};

var hospitalAff1 = new UsersInHospital
{
    UserID = user.UserID,
    HospitalID = Guid.Parse(hospitalAff1),
    IsEmployed = Boolean.Parse(isEmployed1)
};

user.UsersInHospitals.Add(hospitalAff1);

var hospitalAff2 = new UsersInHospital
{
    UserID = user.UserID,
    HospitalID = Guid.Parse(hospitalAff2),
    IsEmployed = Boolean.Parse(isEmployed2)
};

user.UsersInHospitals.Add(hospitalAff2);

此外,您不需要在UsersInHospital对象中指定 UserId。如果您正确设置了主键和外键,实体框架将为您完成这项工作。然后您的代码可能如下所示:

var user = new User
{
    UserID = Guid.NewGuid(), 
    Address = employmentAddress.Trim(), 
    ZipCode = int.Parse(zipcode.Trim()),
    UsersInHospitals = new List<UsersInHospital> //or array or whatever it is
    {
        new UsersInHospital
        {
            HospitalID = Guid.Parse(hospitalAff1),
            IsEmployed = Boolean.Parse(isEmployed1)
        },
        new UsersInHospital
        {
            HospitalID = Guid.Parse(hospitalAff2),
            IsEmployed = Boolean.Parse(isEmployed2)
        }
    }
};
于 2013-10-26T11:10:32.017 回答
0

我知道是什么问题。

实际上,我正在添加具有相同 HospitalID 的 UsersInHospitals,这造成了重复实体的问题

感谢@Darko 更正“UserID = user.UserID”,因为它是由 EF 自动添加的。

我已经编辑了我的问题以实际显示问题。很抱歉没有在问题中显示此问题

于 2013-10-26T11:31:26.783 回答