EF 6尝试两次插入对象

时间:2016-10-10 13:21:05

标签: asp.net-mvc entity-framework entity-framework-6

我是使用实体框架的新手,我们已经准备好首先使用EF6模型添加我们的应用程序。 我有一个这样的类(我已经简化了代码以便更好地解释):

class Country
{
 int CountryId (identity column) { get; set; }
 string Name { get; set; }
 ICollection<Child> Regions { get; set; }
}

class Region
{
 int RegionId (identity column) { get; set; }
 string Name { get; set; }
 int CountryId { get ; set; } //foreign key to Country(CountryId)
}

在应用程序的业务层中,我们初始化对象Region,如下所示:

public Region Create()
{
 Provincia Region = new Region ();
 provincia.Country = CountryDAL.GetByCode("ES");
 provincia.CountryId = Region.Country.CountryId ;

 return Region ;
}

CountryDAL是从数据库加载国家/地区的图层。 当我尝试saveChanges时,我有一个来自数据库的唯一约束异常,因为EF试图插入国家两次。我不明白为什么

this.context.Entry(entity).State = Data.Entity.EntityState.Added;
entity.AcceptChanges(user);
int Result = this.context.SaveChanges();

我只想保存实体Region,其属性CountryId已填充,我不想将Country保存为新对象。 但是,在其他视图中,我应该能够创建一个国家并将他们的国家保存为孩子(但这是我已经解决的另一个问题)。

非常感谢

1 个答案:

答案 0 :(得分:0)

首先,我认为你的代码没有编译。您在Create()方法中有错误。有类型Region,您可以将其用作变量名称。

其次,您在create方法中设置导航属性(Country)和外键值(CountryId)。您只需分配CountryId属性即可。因此,在我看来,这应该有效:

public Region Create()
{
    var country = CountryDAL.GetByCode("ES");
    Region provincia = new Region();
    provincia.CountryId = country.CountryId;

    return Region;
}

我还建议您不要加载所有Country实体。而不是它,创建一个只返回基于&#34; ES&#34;的国家ID的查询。字符串。