创建具有关系的实体时出错

时间:2013-10-26 11:06:43

标签: c# asp.net entity-framework-4

首先,错误是“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.我怀疑我将不得不为每个医院实体单独创建变量

2 个答案:

答案 0 :(得分: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)
        }
    }
};

答案 1 :(得分:0)

我知道这是什么问题。

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

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

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