![](/img/trans.png)
[英]How do I join more than one files, in a Linq (C#) where one of the joins is a left join
[英]More than one record is updated EF-Linq C#
我有下表:
我有幾個數組,如果數據匹配以減少其數量,我將在其中滾動:
//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
具有相同的信息)
屏幕斷點
只有cod_parte是主鍵
這就是問題。
一個主鍵必須是唯一的,但是在您的情況下,您有多個具有相同cod_parte
記錄。 因此,它甚至都不是關鍵,更不用說主要了。
當您調用SaveChanges()
,EF將生成一條帶有WHERE子句的SQL語句,該子句包含主鍵,並且不包含其他任何內容,並假定主鍵將完全標識一條記錄。 這種假設是錯誤的,因為您的“主鍵”實際上並不是鍵。
對於這個表,你至少需要的復合主鍵cod_parte
和rollo
,或者像羅伯特指出,一個真正的合成主鍵。
另請參閱如何在EF中指定復合鍵 。
請檢查您的傳遞數據,如果僅傳遞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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.