我有下表:
我有几个数组,如果数据匹配以减少数量,我将在其中滚动:
//DISMINUYE CANTIDAD DE CASILLER
public void disminuyeCasiller(string[] codParte, string [] rolls, double[] cantResta)
{
int size = codParte.Length;
for(int i = 0; i < size; i++)
{
string parte = codParte[i];
string rol = rolls[i];
double valorRes = cantResta[i];
using(var ctx=new ModelContext())
{
Casiller updateRollo = ctx.Casillers.Where(x => x.cod_parte == parte && x.rollo == rol).First();
double newValue = updateRollo.cantidad - valorRes;
updateRollo.cantidad = newValue;
ctx.SaveChanges();
}
}
}
根据此代码的作用,首先要知道排列的大小(所有数组都将具有相同的大小),创建一个for
并在rollo
和cod_parte
的匹配项,在这种情况下,您恢复的金额300
将减去cantResta
中到达的数字,例如100.50
,一旦在该位置分配了减法,保存更改,并在必要时重复,直到一切正常为止。
我正在传递此数据:
codparte[]=new array{"11155"};
rollos[]=new array{"RT0102"};
cantRest[]=new array{100.50};
//Size and data can be different -only a example
在表中的cantidad
和rollo RT0102
的结尾处,我应该像这样:199.50
,问题是更新两条记录,看起来像这样:
当未选择此行时,为什么还要更新RT0103
?我这句话做错了什么? (将来可能会出现问题,因为许多rollos
具有相同的信息)
屏幕截图断点
答案 0 :(得分:3)
只有cod_parte是主键
这是问题所在。
主键必须是唯一的,但是在您的情况下,您有多个记录具有相同的cod_parte
。因此,它甚至都不是键,更不用说是主键了。
当您调用SaveChanges()
时,EF会生成一个带有WHERE子句的SQL语句,该子句包含主键,并且不包含其他任何内容,并假定主键将完全标识一条记录。这种假设是错误的,因为您的“主键”实际上并不是键。
对于此表,您需要一个至少为cod_parte
和rollo
的复合主键,或者,正如罗伯特(Robert)所指出的那样,是一个真正的合成主键。
答案 1 :(得分:0)
请检查您传递的数据,如果仅传递codParte=111555,rolls=RT0102,cantRest=100.50
,则不会更新RT0103
。
例如:
public class Test{
public static void Main(){
disminuyeCasiller(new[] { "111555"}, new[] { "RT0102"}, new[] {100.50});
}
public static void disminuyeCasiller(string[] codParte, string[] rolls, double[] cantResta)
{
int size = codParte.Length;
for (int i = 0; i < size; i++)
{
string parte = codParte[i];
string rol = rolls[i];
double valorRes = cantResta[i];
Console.WriteLine($"parte {parte}/rol {rol}/valorRes {valorRes}"); //Result:parte 111555/rol RT0102/valorRes 100.5
}
}
}