[英]How to select and update specific columns by Entity Framework Core?
我現在正在嘗試將原始 SQL 轉換為 EF 核心。 我的表有很多列,例如column1到10,我需要選擇和更新特定的列。 像這樣的原始代碼:
SELECT column1, column2 FROM table WHERE key = "someKey"
(processing data)
UPDATE table SET column2 = someValue WHERE key = "someKey"
首先,我試過這樣:
var query =
from model in context
where key == "someKey"
select model;
query.First().column2 = someValue;
context.SaveChanges();
這段代碼如我所願工作得很好,但生成的 SQL 是這樣的:
SELECT key, column1, column2, ... column10 FROM table WHERE key = "someKey"
我不想選擇無用的列,所以我嘗試了這個:
var query =
from model in context
where key == "someKey"
select new myDTO
{
Item1 = model.column1,
Item2 = model.column2
};
query.First().Item2 = someValue;
context.SaveChanges();
此代碼完全按照我的意願生成 SELECT SQL 語句,但無法生成更新語句。 (顯然,myDTO 沒有注冊到 DbContext 中)如何使用 EF Core 執行此操作?
您可以使用Attach
和Entry
方法來跟蹤對實體模型的更改。 要識別模型,您需要所有鍵(這里我只考慮一個主鍵: Id
)
var query =
from model in context
where key == "someKey"
select new myDTO
{
Id = model.Id,
Item1 = model.column1,
Item2 = model.column2
};
var dto = query.First();
// Here I'm using Entity but you should use the right type
var entityyModified = new Entity();
entityModified.Id = dto.Id;
entityyModified.Item1 = dto.Item1;
entityyModified.Item2 = dto.Item2;
// ...
// Item1 or Item2 properties can be assigned to different values
// ...
// Save the changes
context.Attach(entityyModified);
var dbEntry = context.Entry(entityyModified);
dbEntry.Property(e => e.Item1).IsModified = true;
dbEntry.Property(e => e.Item2).IsModified = true;
context.SaveChanges();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.