gpt4 book ai didi

entity-framework-4 - 尝试使用 EF 4 迭代添加对象时出现 System.InvalidOperationException

转载 作者:行者123 更新时间:2023-12-01 05:42:20 25 4
gpt4 key购买 nike

这个问题与 this one 非常相似.但是,该问题的解决方案:

  • 似乎不适用,或
  • 有点怀疑,似乎不是解决问题的好方法。

  • 基本上,我遍历对象的通用列表,并插入它们。使用带有默认代码生成的 MVC 2、EF 4。
    foreach(Requirement r in requirements)
    {
    var car = new CustomerAgreementRequirement();
    car.CustomerAgreementId = viewModel.Agreement.CustomerAgreementId;
    car.RequirementId = r.RequirementId;
    _carRepo.Add(car); //Save new record
    }

    和 Repository.Add() 方法:
    public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
    {
    private TxRPEntities txDB;
    private ObjectSet<TEntity> _objectSet;

    public void Add(TEntity entity)
    {
    SetUpdateParams(entity);
    _objectSet.AddObject(entity);
    txDB.SaveChanges();
    }

    我应该注意到,我已经在整个代码中成功地使用了 Add() 方法来进行单次插入;这是我第一次尝试使用它来迭代地插入一组对象。

    错误:

    System.InvalidOperationException: The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.



    如上一个问题所述,EntityKey 设置为 True,StoreGeneratedPattern = Identity。插入的实际表是一个关系表,因为它由一个身份字段和两个外键字段组成。错误总是发生在 第二插入,无论之前是否插入了该特定实体,我都可以确认值总是不同的,就数据库而言没有键冲突。我怀疑它与在实际插入之前设置的临时实体 key 有关,但我不知道如何确认,也不知道如何解决它。

    我的直觉是,上一个问题中将 SaveOptions 设置为 None 的解决方案不是最好的解决方案。 (见之前的讨论 here )

    最佳答案

    我的存储库也使用循环遇到了这个问题,并认为这可能是由一些奇怪的类似种族的条件引起的。我所做的是重构一个 UnitOfWork 类,以便 repository.add() 方法严格添加到数据库中,但不存储上下文。因此,存储库只负责集合本身,并且对该集合的每个操作都发生在工作单元的范围内。

    那里的问题是:在一个循环中,你用 EF4 很快就会耗尽内存。因此,您确实需要定期存储更改,我只是不会在每次保存后存储。

    公共(public)类 BaseRepository : IRepository 其中 TEntity : 类
    {
    私有(private) TxRPEntities txDB;
    私有(private)对象集_objectSet;

    public void Add(TEntity entity)
    {
    SetUpdateParams(entity);
    _objectSet.AddObject(entity);
    }

    public void Save()
    {
    txDB.SaveChanges();
    }

    然后你可以做类似的事情
    foreach(Requirement r in requirements)
    {
    var car = new CustomerAgreementRequirement();
    car.CustomerAgreementId = viewModel.Agreement.CustomerAgreementId;
    car.RequirementId = r.RequirementId;
    _carRepo.Add(car); //Save new record
    if (some number limiting condition if you have thousands)
    _carRepo.Save(); // To save periodically and clear memory
    }

    _carRepo.Save();

    注意:我不是很喜欢这个解决方案,但我四处寻找,试图找出为什么事情在其他地方工作时会出现循环,这是我想出的最好的解决方案。

    关于entity-framework-4 - 尝试使用 EF 4 迭代添加对象时出现 System.InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4675603/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com