所以,我希望这很简单。我想出了一种存储断开连接的实体的方法(由于我的情况非常特殊),并且为了工作,我想在for循环中创建一个带有这些值的Dictionary。
但是我得到了#34;一个具有相同键的项目"已添加问题,我不知道为什么。
我尝试过以下方法:
Dictionary<int, EntityState> StateProduct = new Dictionary<int, EntityState>();
for (int s = 0; s < userProducts.Count; s++ ) //userProducts.Count had value of 3
{
StateProduct.Add(s, EntityState.Modified);
}
但我收到错误:
其中:
我真的不知道发生了什么......
编辑:以下是完整的代码
var dbIboID = dbs.OrderDB.Where(x => x.OrderID == Order[0].OrderID).FirstOrDefault();
if(dbIboID.IboID != uid)
{
return false;
}
//2nd Step:
//2.0 Attach it. Yes I know it sets it as unchanged. But let me do the magic trick!!!
dbIboID.OrderProcess = Order.ToList(); //CHANGED
dbs.OrderDB.Attach(dbIboID);
//2.1 Extract original values from the database.
var originalProducts = dbs.OrderProcessDB.Where(x => x.OrderProcessID == Order[0].OrderProcessID).ToList();
var userProducts = Order.ToList();
//This is a dictionary which will be used to set all other entities with their correct states!
Dictionary<int, System.Data.Entity.EntityState> StateProduct = new Dictionary<int, System.Data.Entity.EntityState>();
//2.3 Find new added products. addedProducts = userProducts[key] - originalProducts[key]
if(userProducts.Count > originalProducts.Count)
{
for (int i = originalProducts.Count - 1; i < userProducts.Count; i++ )
{
StateProduct.Add(i, System.Data.Entity.EntityState.Added);
}
}
//2.3 Find Deleted products = originalProducts - userProducts. Do reverse of the addedProducts
else
{
for (int i = userProducts.Count - 1; i < originalProducts.Count; i++)
{
StateProduct.Add(i, System.Data.Entity.EntityState.Deleted);
}
}
//2.4 Find modified products modifiedProducts = [userProducts - addedProducts] different originalProducts
//This is not 100% fool proof. Because there will be times that I will always have a modification,
// when objects remained unchanged.
for (int s = 0; s < userProducts.Count; s++ )
{
StateProduct.Add(s, System.Data.Entity.EntityState.Modified);
}
//2.5 Painting Process:
for (int i = 0; i < dbIboID.OrderProcess.Count(); i++ )
{
dbs.DB.Entry(dbIboID.OrderProcess[i]).State = StateProduct[i];
}
答案 0 :(得分:1)
您所显示的代码不应该产生该异常,因为字典是在循环之前立即分配的,因此应该为空,并且所有添加的项都是唯一的整数。
我的猜测是字典中已经有了一些值。如果是这样,那么使用Add
设置值会抛出ArgumentException
,因为与该键对应的值只能替换,而不是已添加,对于Dictionary
类,每个键只允许一个值。
因此,如果您希望字典不具有键的值,并且希望抛出错误异常,请执行以下操作:
StateProduct.Add(s, EntityState.Modified)
如果要添加或替换值,请执行:
StateProduct[s] = EntityState.Modified;