I want to convert my SQL query to lambda expression.Below is the SQL query.I tried but failing to get expected result
UPDATE
Sales
SET
SI.ACP= SD.ACP
FROM
Sales SI
INNER JOIN
SaleDesc SD
ON
SI.GroupID= SD.GroupID;
I want to convert my SQL query to lambda expression.Below is the SQL query.I tried but failing to get expected result
UPDATE
Sales
SET
SI.ACP= SD.ACP
FROM
Sales SI
INNER JOIN
SaleDesc SD
ON
SI.GroupID= SD.GroupID;
EF Core itself does not support bulk and native updates and everything should go through ChangTracker.
Anyway, you can use available extensions for EF Core, which can do that without raw SQL execution. For example linq2db.EntityFrameworkCore (disclaimer: i’m one of the creators)
Then you can write the following LINQ query:
var queryForUpdate =
from si in ctx.Sales
join sd in ctx.SalesDesc on si.GroupID equals sd.GroupID
select new { si, sd }
queryForUpdate
.Set(u => u.si.ACP, u => u.sd.ACP)
.Update();
Sales must have a PK. you have different ways to write LINQ. this is one of the approaches (i try to make it more readable for you.)
Sales.Dump("original");
Sales
.Join(
SaleDescs,
sales => sales.GroupID,
desc => desc.GroupID,
(sales, desc) => new { Sales = sales, SaleDesc = desc }
)
.ToList()
.ForEach(s =>
{
Sales.Where(sl => sl.GroupID == s.Sales.GroupID).FirstOrDefault().ACP = s.SaleDesc.ACP;
});
SubmitChanges();
Sales.Dump("resulted");
since I have no details on table structure - i made up some for this example
use
using (var db = new MyContext())
{
var p = db.Sales
.Join(db.SaleDesc,
left => left.GroupID,
right => right.GroupID,
(left, right) => new { Sales = left, ACP = right.ACP });
foreach (var item in p)
{
item.Sales.ACP = item.ACP;
db.Sales.Attach(item.Sales);
db.Entry(item.Sales).State = EntityState.Modified;
db.SaveChanges();
}
}
or
using (var db = new MyContext())
{
db.Sales
.Join(db.SaleDesc,
left => left.GroupID,
right => right.GroupID,
(left, right) => new { Sales = left, ACP = right.ACP }).ForEachAsync(a => a.Sales.ACP = a.ACP);
db.SaveChanges();
}