所以我尝试的是只从表中获取那些必须更新的列,我尝试如下:
var user = (from u in context.tbl_user where u.e_Id == model.Id select
new { u.first_name, u.last_name, u.role, u.email, u.account_locked })
.FirstOrDefault();
但是当我尝试为获取的数据分配新值时,如下所示
user.first_name = model.FirstName;
我看到下面显示错误
Property or indexer 'anonymous type: string first_name, string last_name, string role, string email, bool account_locked.first_name' cannot be assigned to -- it is read only
但是当我从表中检索所有值而不进行如下过滤时,它工作正常。
var user = (from u in context.tbl_user where u.e_Id == model.Id select u).FirstOrDefault();
为什么它不适用于第一次查询。我在许多网站上读到,就性能和安全性而言,从数据库中只检索所需的属性是很好的。但是我真的无法理解我选择的第一种方法有什么问题。非常感谢任何解释。
更新
有没有其他方法可以只获取所需的列并更新它们并将它们存储回去?
最佳答案
Anonymous Types属性是只读的,因此您无法更改它们。
停止做 micro-optimizing或 premature-optimization在你的代码上。尝试编写正确执行的代码,然后如果您稍后遇到性能问题,则分析您的应用程序并查看问题出在哪里。如果您有一段代码由于寻找最短和最长的字符串而出现性能问题,那么请开始优化这部分。
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3% - Donald Knuth
如果您只想获取特定的列,您可以创建一个自定义类并像其他人提到的那样在您的查询中填写属性。
关于c# - 使用 LINQ 仅从表中获取所需的列以修改和保存记录会出现典型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32542539/