// Select all fields to update
using (var db = new Entities())
{
// dbFields are trusted values
var query = db.tblRecords
.Where("id == " + f.id)
.Select("new(" + string.Join(",", dbFields.Keys) + ")");
foreach (var item in query)
{
foreach (PropertyInfo property in query.ElementType.GetProperties())
{
if (dbFields.ContainsKey(property.Name))
{
// Set the value to view in debugger - should be dynamic cast eventually
var value = Convert.ToInt16(dbFields[property.Name]);
property.SetValue(item, value);
// Something like this throws error 'Object does not match target type'
// property.SetValue(query, item);
}
}
}
db.SaveChanges();
}
运行时的上述代码不会导致对DB的任何更改。显然这段代码需要一些清理,但我试图让基本功能正常工作。我相信我可能需要做的是以某种方式重新申请' item'回到'查询'但是,无论我尝试什么样的实施,我都没有运气,但我总是收到'对象与目标类型不匹配'。
这个半相似的问题重申了这一点,但对我来说并不是很清楚,因为我使用动态LINQ查询并且不能直接引用属性名称。 https://stackoverflow.com/a/25898203/3333134
答案 0 :(得分:1)
实体框架将为您执行实体更新,而不是自定义结果。您的tblRecords
拥有许多实体,如果您希望实体框架提供帮助,这就是您想要操作的内容。删除您的投影(对Select
的调用),查询将直接返回对象(列数过多,是的,但我们稍后将介绍这些内容)。
动态更新的执行方式与C#中的任何其他动态分配相同,因为您有一个正常的对象可以使用。实体框架将跟踪您所做的更改,并在调用SaveChanges
时生成并执行相应的SQL查询。
但是,如果您想首先优化并停止在内存中选择和创建所有值,即使是那些不需要的值,您也可以从内存中执行更新。如果您自己创建了正确类型的对象并分配了正确的ID,则可以使用Attach()方法将其添加到当前上下文中。从那时起,Entity Framework将记录任何更改,当您调用SaveChanges
时,应将所有内容发送到数据库:
// Select all fields to update
using (var db = new Entities())
{
// Assuming the entity contained in tblRecords is named "ObjRecord"
// Also assuming that the entity has a key named "id"
var objToUpdate = new ObjRecord { id = f.id };
// Any changes made to the object so far won't be considered by EF
// Attach the object to the context
db.tblRecords.Attach(objToUpdate);
// EF now tracks the object, any new changes will be applied
foreach (PropertyInfo property in typeof(ObjRecord).GetProperties())
{
if (dbFields.ContainsKey(property.Name))
{
// Set the value to view in debugger - should be dynamic cast eventually
var value = Convert.ToInt16(dbFields[property.Name]);
property.SetValue(objToUpdate, value);
}
}
// Will only perform an UPDATE query, no SELECT at all
db.SaveChanges();
}
答案 1 :(得分:0)
执行SELECT NEW ...
时,它只选择特定字段,不会为您跟踪更新。我认为如果你将你的查询改为这样就可以了:
var query = db.tblRecords.Where(x=>x.id == id);