如何按实体框架核心选择和更新特定的列?
我现在正在尝试将RAW SQL转换为EF Core。 我的表有许多列,例如第1至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();
此代码生成了我希望的SQL语句,但是无法生成更新语句。 (显然,MyDTO未注册到DBContext) 我该如何使用EF核心进行操作?
I'm trying to convert raw SQL to EF core now.
my table has many columns, such as column1 to 10, and I need to select and update specific columns. original code like this :
SELECT column1, column2 FROM table WHERE key = "someKey"
(processing data)
UPDATE table SET column2 = someValue WHERE key = "someKey"
first, I tried like this :
var query =
from model in context
where key == "someKey"
select model;
query.First().column2 = someValue;
context.SaveChanges();
this code works very fine as I wished, but SQL generated like this :
SELECT key, column1, column2, ... column10 FROM table WHERE key = "someKey"
I do not want select useless columns so I tried this:
var query =
from model in context
where key == "someKey"
select new myDTO
{
Item1 = model.column1,
Item2 = model.column2
};
query.First().Item2 = someValue;
context.SaveChanges();
this code generates SELECT SQL statement exactly I wished, but cannot generate update statement. (obviously, myDTO is not registered into DbContext)
How can I do this with EF Core?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
附加
和条目
方法来跟踪对实体模型的更改。要确定模型您需要所有键You can use
Attach
andEntry
methods to track the changes to a entity model. To identify the model you would need all the keys (here I'm considering only one primary key:Id
)