【问题标题】:EF 6 Tries to insert an object twiceEF 6 尝试插入一个对象两次
【发布时间】:2016-10-11 05:20:04
【问题描述】:

我是使用实体框架的新手,我们正在尝试将我们的应用程序添加到首先使用 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)
}

在应用程序的业务层中,我们像这样初始化对象区域:

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

 return Region ;
}

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

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

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

非常感谢

【问题讨论】:

  • 如果要保存,是否需要添加到上下文中?您可以将其保存(如果已附加)或将其附加到不跟踪它的上下文?
  • 感谢您的回答。我不明白。你能解释一下吗?你指的是“this.context.Entry(entity).State = Data.Entity.EntityState.Added;”这一行吗
  • 是的。我不是 EF 专家,但如果你想保存一个实体,你必须附加它(如果它还没有)或直接致电 SaveChanges()Add() 更像是数据库中的 INSERT。如果它存在于您的数据库中,而不是您的上下文中,则调用Add() 不会损害您的上下文,但是将现有项目插入数据库是错误的。我使用 Add()Data.Entity.EntityState.Added: 传递。

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


【解决方案1】:

首先,我认为您的代码无法编译。您在 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 实体。取而代之的是,创建一个仅返回基于“ES”字符串的国家/地区 id 的查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    相关资源
    最近更新 更多