Entity Framework genera una consulta inapropiada

I am using EntityFramework 4. I am facing strange issue with entity framework, here is the code:

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

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


Let's say existing item is found and DeleteTime is set for this item. (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...

Tiene este aspecto:

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

Estructura de la mesa:

(index)LeftItem int
(index)RightItem int
(index)DeleteTime datetime?

What am I missing? please help!

preguntado el 23 de abril de 13 a las 13:04

Cual es el tipo de DeleteTime? -

Could you share this generated query? -

DeleteTime is nullable DateTime (DateTime?) -

Could you add the structure of your table Link? I think your table has no PK. -

Is the generated class Link also have the Id generated field? Try to recreate your ObjectContext. Could you show the definition of Link? -

2 Respuestas

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 con el WHERE clause you give
  2. An update query 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. Check the implementation of the Link class.

Respondido 23 Abr '13, 13:04

Thanks for the answer, but I have primary key. Really, query looks weird - Andrés

Thanks to Scorpi0 and 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

Respondido 23 Abr '13, 13:04

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.