如何在linq中编写“ in(select ”方法?
我正在尝试转换:
UPDATE ActualAmountsByLocation SET isCustomerItem=1 WHERE ItemBarcode IN (SELECT barcode FROM StockMaterials WHERE barcode=@Barcode AND ownership=1)
我试过这样:
Array stockMaterials = ( from s in stockMovementCtx.StockMaterials where s.barcode == Barcode && s.ownership ==1 select s).ToArray();
actualAmountsByLocation = (from a in stockMovementCtx.ActualAmountsByLocations
where a.ItemBarcode.Contains(stockMaterials)
select a).First();
答案 0 :(得分:2)
要获得IN查询,您需要反转包含的含义。此外,无需实现第一个查询IMO。
var stockMaterials = from s in stockMovementCtx.StockMaterials
where s.barcode == Barcode && s.ownership ==1
select s;
actualAmountsByLocation = (from a in stockMovementCtx.ActualAmountsByLocations
where stockMaterials.Contains( a.ItemBarcode)
select a).First();
答案 1 :(得分:1)
你快到了。
移除.ToArray
调用以阻止查询直接执行,并制作stockMaterials
类型的IQueryable<StockMaterial>
变量。
答案 2 :(得分:0)
这是你在找什么?
ActualAmountsByLocation = StockMaterials.Where(s => s.barcode == Barcode && s.ownership == 1).ToArray();
答案 3 :(得分:0)
var stockMaterials = (from s in stockMovementCtx.StockMaterials
where s.barcode == Barcode && s.ownership == 1
select s).ToArray();
var actualAmountsByLocation = (from a in stockMovementCtx.ActualAmountsByLocations
where stockMaterials.Contains(a.ItemBarcode)
select a).First();
答案 4 :(得分:0)
希望下面的代码示例对您有所帮助
// these are using linq methods
var barcodes = stockMovementCtx.StockMaterials
.Where(s => s.barcode == Barcode && s.ownership == 1)
.Select(s => s.barcode);
var amounts = stockMovementCtx.ActualAmountsByLocations
.Where(a => barcodes.Contains(a.ItemBarCode))
.FirstOrDefault();
// if you would like to use the query expressions instead, here they are
//var barcodes = from s in stockMovementCtx.StockMaterials
// where s.barcode = Barcode && s.ownership == 1
// select s.barcode;
//var amounts = (from a in stockMovementCtx.ActualAmountsByLocations
// where barcodes.Contains(a.ItemBarCode.Contains)
// select a).FirstOrDefault();
// helpful to use FirstOrDefault if you are not sure that the query will return a result
if (amounts != null) {
// change value
amounts.IsCustomerItem = 1;
// update database
stockMovementCtx.SubmitChanges();
}
答案 5 :(得分:0)
在LinQ上进行更新非常简单,例如,请查看下面的代码块。
var user = (from s in dataContext.USERS
调用用户表,并设置条件。
where s.UserId.Equals(id)
select s).FirstOrDefault();
我想对用户电子邮件进行更改。(不要忘记这一点:如果使用ToList()调用,则需要控制列表计数以避免例外:if(user.Count&gt; 0)..)< / p>
更新用户:
s.EmailAddress = serkan@serkanhekimoglu.com;
dataContext.SubmitChanges();
,您的数据将在SubmitChanges();
之后更新