更新上下文以反映强类型查询中的更改 [英] Updating context to reflect changes in strong typed query

查看:66
本文介绍了更新上下文以反映强类型查询中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 


我的网络应用程序中包含以下代码:


 


 


EntityObj db = new  EntityObj();


IEnumerable< CustomQueryType> QueryResultSet =来自db.Table.ToList()中的q,其中q.Index == 1选择新的QueryListingBlogEntryType(q.Index,q.Title,q.Value,q.Value2,q.Value3);


//添加ToList()以参数化强类型类而不是匿名类型)

 

解决方案

< blockquote>

这里有一些问题。首先,由于您投射到自己的课程中,您将无法利用实体框架的固有变化跟踪能力。因此,更改CustomQueryType不会更改
Entity Framework跟踪的任何内容,保存更改将不会执行任何操作。


第二个问题是您不需要在调用SaveChanges之前调用AcceptAllChanges。这样做是将指示更改(已添加,已修改,已删除)的所有状态重置为未更改。然后,调用SaveChanges会导致实体框架看到
的更改,此时没有,因为您调用了AcceptAllChanges。


第二个问题很容易解决。在调用SaveChanges之前,不要调用AcceptAllChanges。


第一个更难一点。由于您在Web环境中使用它,因此可以查询EF返回的实际实体对象,更改其属性,然后保存更改。伪代码如下所示:


var changedEntity = //这来自用户提交回网站的任何内容。

using(EntityObj db = new EntityObj ())

{

     var originalEntity = db.Table.Single(t => t.Id == changedEntity.Id);

     originalEntity.Value = changedEntity.Value;

     originalEntity.Value2 = changedEntity.Value2;

     //依旧...设置所有已更改的属性。

    

     db.SaveChanges();

}


 

I have the following code in my web application:

 

 

EntityObj db= new EntityObj();

IEnumerable<CustomQueryType> QueryResultSet = from q in db.Table.ToList() where q.Index== 1 select new QueryListingBlogEntryType(q.Index, q.Title, q.Value, q.Value2, q.Value3);

//added ToList() to have parameterized strongly type classes instead of anonymous types)

 

解决方案

There are a few issues here. The first is that since you are projecting into your own class you won't be able to leverage the innate change tracking ability of the Entity Framework. As a result changing the CustomQueryType doesn't change anything that the Entity Framework tracks, and saving changes will not do anything.

The second issue is that you don't need to call AcceptAllChanges before calling SaveChanges. What that does is reset all the states that indicate change (Added, Modified, Deleted) to Unchanged. Then, calling SaveChanges causes the Entity Framework to look for changes, at which point there are none, since you called AcceptAllChanges.

The second issue is easy to work around. Simply don't call AcceptAllChanges before calling SaveChanges.

The first is a little more difficult. Since you're using this in a web environment, you can query for the actual entity object that EF returns, change its properties, and then save the changes. Pseudo-code looks like this:

var changedEntity = // This comes from whatever the user submitted back to the site.
using (EntityObj db = new EntityObj())
{
    var originalEntity = db.Table.Single(t => t.Id == changedEntity.Id);
    originalEntity.Value = changedEntity.Value;
    originalEntity.Value2 = changedEntity.Value2;
    // And so on...setting all the properties that changed.
    
    db.SaveChanges();
}


这篇关于更新上下文以反映强类型查询中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆