通过匿名类型更新数据库?
以下代码从我的“活动”表中获取尚未发布到 Twitter 上的所有行。然后它循环遍历并发布每一行的 Twitter 更新。在此过程中,我想更新数据库以指示这些行现在已被“推特”。
但是,当我尝试更新此值时,出现错误(如下所示)。我认为这是因为我使用的是匿名类型。但是,如果我使用完整类型,则需要从数据库中提取大量不必要的数据。
有没有办法有效地完成这个任务?或者这是 EF 迫使我在性能上做出妥协的又一案例?
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
}
}
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.
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试这样的“假对象方法”:
这是“理论”代码,不确定它是否有效。
编辑
不再是“理论”。我已经使用 EF 4.1 的
DbContext
对此进行了测试,它的工作原理如上面的示例代码中所述。 (因为DbContext
只是ObjectContext
的包装 API,所以几乎可以肯定地假设它也适用于 EF 4.0。)You could try a "fake object approach" like this:
It's "theoretical" code, not sure if it would work.
Edit
Not "theoretical" anymore. I've tested this with
DbContext
of EF 4.1 and it works as described in the sample code above. (BecauseDbContext
is only a wrapper API aroundObjectContext
it's almost safe to assume that it also will work in EF 4.0.)如果您只是选择“行动”,那么它应该可以工作。编辑完成后别忘了提交。
If you simply select 'act', then it should work. Don't forget to submit after editing.
为什么你调用 select new 而不是返回整个对象。仅当属性在模式资源中正确定义时,实体框架才能够更新属性,而匿名类型当然不是这样。
实体框架永远无法确定属性映射到哪个表和哪个字段。
Why are you calling select new instead of returning entire object. Entity framework will only be able to update property if it is correctly defined in schema resources which certainly is not case with anonymous type.
Entity framework will never be able to determine which table and which field the property is mapped to.