c# - Entity Framework 4 CRUD 创建错误

标签 c# entity-framework

我的数据库中有 3 个相关表。

Farm ----> FarmCrops <----- 农裁剪

我正在尝试使用农裁剪集合更新农场实体,但遇到了问题。我已经为此工作了几个小时,但没有成功,所以非常感谢任何帮助。

我收到的错误是这样的:

The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state.

我的更新逻辑如下(代码量大请见谅,尽量说清楚):

            bool isNew = false;
            Farm farm;

            // Insert or update logic.
            if (viewModel.Farm.FarmId.Equals(Guid.Empty))
            {
                farm = new Farm
                {
                    FarmId = Guid.NewGuid(),
                    RatingSum = 3,
                    RatingVotes = 1
                };
                isNew = true;
            }
            else
            {
                farm = this.ReadWriteSession
                       .Single<Farm>(x => x.FarmId == viewModel.Farm.FarmId);

            }

            // Edit/Add the properties.
            farm.Name = viewModel.Farm.Name;
            farm.Owner = viewModel.Farm.Owner;
            farm.Address = viewModel.Farm.Address;
            farm.City = viewModel.Farm.City;
            farm.Zip = viewModel.Farm.Zip;
            farm.WebAddress = viewModel.Farm.WebAddress;
            farm.PhoneNumber = viewModel.Farm.PhoneNumber;
            farm.Hostel = viewModel.Farm.Hostel;
            farm.Details = viewModel.Farm.Details;
            farm.Latitude = viewModel.Farm.Latitude;
            farm.Longitude = viewModel.Farm.Longitude;
            farm.Weather = viewModel.Farm.Weather;

            // Add or update the crops.
            string[] cropIds = Request.Form["crop-token-input"].Split(',');
            List<Crop> allCrops = this.ReadWriteSession.All<Crop>().ToList();

            if (!isNew)
            {
                // Remove all previous crop/farm relationships.
                farm.Crops.Clear();
            }

            // Loop through and add any crops.
            foreach (Crop crop in allCrops)
            {
                foreach (string id in cropIds)
                {
                    Guid guid = Guid.Parse(id);
                    if (crop.CropId == guid)
                    {
                        farm.Crops.Add(crop);
                    }
                }
            }

            if (isNew)
            {
                this.ReadWriteSession.Add<Farm>(farm);
            }
            else
            {
                this.ReadWriteSession.Update<Farm>(farm);
            }
            this.ReadWriteSession.CommitChanges();

我在 ReadWriteSession 中的更新代码非常简单(GetSetName<T> 只是从它的 PropertyInfo 返回类型名称。):

    /// <summary>
    /// Updates an instance of the specified type.
    /// </summary>
    /// <param name="item">The instance of the given type to add.</param>
    /// <typeparam name="T">The type of entity for which to provide the method.</typeparam>
    public void Update<T>(T item) where T : class, new()
    {
        this.context.AttachTo(this.GetSetName<T>(), item);
        this.context.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
    }

最佳答案

您正在添加现有的 Crop对象(来自 allCrops 列表)到新的 Farm .当您将新实体连接到现有实体时,新实体会自动附加到上下文。因此,当您尝试附加 Farm 时出现错误第二次到上下文。

Add<Farm>(farm)代码中的语句甚至不需要连接 Farm到上下文,如果你有一个现有的 Farm从上下文加载的,它已经附加到上下文。

整个if (isNew)声明是不必要的。 Entity Framework 本身跟踪对象状态,因此您无需设置修改后的状态。

关于c# - Entity Framework 4 CRUD 创建错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5529733/

相关文章:

c# 预编译大数组或其他解决方案以将大数据嵌入可执行文件

c# - 正则表达式 + 删除匹配前的所有文本

c# - 将 JSON 数据写入 HttpWebRequest 时收到 "Request was cancelled"错误

c# - 没有连接字符串的代码优先更改数据源

c# - 优先使用mysql数据库的 Entity Framework

c# - 如何使用 Task 设置最大并发线程数

c# - .NET Web 服务客户端调用性能问题

c# - asp.net core dbcontext 在计时器结束时被释放

entity-framework - EF Code First - 先删除再创建数据库

asp.net-mvc - 未找到类型 'System.Data.Entity.Infrastructure.SqlConnectionFactory' 的构造函数