通过匿名类型更新数据库? [英] Updating Database via Anonymous Type?
问题描述
以下代码从活动"表中获取所有尚未发布到Twitter上的行.然后,它循环遍历并为每个行发布Twitter更新.在此过程中,我想更新数据库以指示这些行现在已被发送".
The following code gets all the rows from my Activities table that have not already been posted on Twitter. It then loops through and posts Twitter updates for each of those row. In the process, I would like to update the database to indicate these rows have now been "twittered".
但是,尝试更新此值时出现错误(如下所示).我认为这是因为我使用的是匿名类型.但是,如果使用完整类型,则需要从数据库中提取很多不必要的数据.
However, I'm getting an error (indicated below) when I try and update this value. I assume this is because I'm using an anonymous type. However, if I use the full type, that will require pulling a lot of unnecessary data from the database.
有没有办法有效地做到这一点?还是这是EF强迫我在性能上做出让步的另一种情况?
Is there a way to accomplish this efficiently? Or is this yet another case where EF forces me to make compromises in performance?
using (MyEntities context = new MyEntities())
{
var activities = from act in context.Activities
where act.ActTwittered == false
select new { act.ActID, act.ActTitle, act.Category,
act.ActDateTime, act.Location, act.ActTwittered };
foreach (var activity in activities)
{
twitter.PostUpdate("...");
activity.ActTwittered = true; // <== Error: ActTwittered is read-only
}
}
推荐答案
您可以尝试使用伪对象方法",如下所示:
You could try a "fake object approach" like this:
using (MyEntities context = new MyEntities())
{
var activities = from act in context.Activities
where act.ActTwittered == false
select new { act.ActID, act.ActTitle, act.Category,
act.ActDateTime, act.Location, act.ActTwittered };
foreach (var activity in activities)
{
twitter.PostUpdate("...");
// Create fake object with necessary primary key
var act = new Activity()
{
ActID = activity.ActID,
ActTwittered = false
};
// Attach to context -> act is in state "Unchanged"
// but change-tracked now
context.Activities.Attach(act);
// Change a property -> act is in state "Modified" now
act.ActTwittered = true;
}
// all act are sent to server with sql-update statements
// only for the ActTwittered column
context.SaveChanges();
}
这是理论上的"代码,不确定是否可行.
It's "theoretical" code, not sure if it would work.
修改
不再是理论"了.我已经使用EF 4.1的 DbContext
测试了它,它的工作方式如上面的示例代码中所述.(因为 DbContext
只是 ObjectContext
的包装API,所以几乎可以肯定地说它也可以在EF 4.0中使用.)
Not "theoretical" anymore. I've tested this with DbContext
of EF 4.1 and it works as described in the sample code above. (Because DbContext
is only a wrapper API around ObjectContext
it's almost safe to assume that it also will work in EF 4.0.)
这篇关于通过匿名类型更新数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!