gpt4 book ai didi

c# - Entity Framework 4 CRUD 创建错误

转载 作者:行者123 更新时间:2023-11-30 13:50:47 26 4
gpt4 key购买 nike

我的数据库中有 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/

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