简体   繁体   English

实体框架生成不适当的查询

[英]Entity Framework generates inappropriate query

I am using EntityFramework 4. I am facing strange issue with entity framework, here is the code: 我正在使用EntityFramework4。我遇到了实体框架的奇怪问题,这是代码:

public void UpdateLink(Link link)
{
     Link existing = ObjectContext
                    .Link
                    .FirstOrDefault(p => p.ItemLeft == link.ItemLeft 
                                      && p.ItemRight == link.ItemRight 
                                      && p.DeleteTime == null);

    if (existing != null)
    {
        existing.DeleteTime = link.DeleteTime;
    }

    ObjectContext.SaveChanges();
}

Let's say existing item is found and DeleteTime is set for this item. 假设找到了现有项目,并为此项目设置了DeleteTime。 (if statement was passed) (如果通过了声明)

Then when SaveChanges is called I get query (with sql profiler) wich updates all the records where ItemLeft is X and ItemRight is Y. In fact it ignores DeleteTime = null condition... 然后,当调用SaveChanges时,我得到查询(使用sql profiler),将更新所有记录,其中ItemLeft为X且ItemRight为Y。实际上,它忽略DeleteTime = null条件...

Looks like that: 看起来像这样:

exec sp_executesql N'update [Link] set [DeleteTime] = @0
where (([ItemLeft] = @1) and ([ItemRight] = @2))
',N'@0 datetime,@1 int,@2 int',@0='2013-04-23 14:58:21.853',@1=857,@2=872

Table structure: 表结构:

ID [PK]
(index)LeftItem int
(index)RightItem int
(index)DeleteTime datetime?

What am I missing? 我想念什么? please help! 请帮忙!

In theory, the update generated base itself on the primary key of the entity. 从理论上讲,更新本身是基于实体的主键生成的。

So your context must have fired in fact two queries: 因此,您的上下文实际上必须触发了两个查询:

  1. A SELECT TOP 1 with the WHERE clause you give 您提供的带有WHERE子句的SELECT TOP 1
  2. An update query WHERE Id = entity.Id 更新查询WHERE Id = entity.Id

The generated query looks very weird, so the main problem is certainly that you don't have a primary key define on your table. 生成的查询看起来很奇怪,所以主要的问题肯定是您的表上没有主键定义。
Another solution is that the mapping between your database and your ObjectContext is totally screwed. 另一个解决方案是数据库与ObjectContext之间的映射完全搞砸了。 Check the implementation of the Link class. 检查Link类的实现。

Thanks to Scorpi0 and Maarten. 感谢Scorpi0和Maarten。 Such problems may arise when table does not contains primary key or there are some primary key differences between context entity and database table 当表不包含主键或上下文实体和数据库表之间存在一些主键差异时,可能会出现此类问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM