Perplexed by an occurrence of the common Entity Framework error
"Attaching an entity of type 'MyType' failed because another entity of the same type already has the same primary key value.
My understanding of this error is that it meant there was another object somewhere in the graph of that object type which had a duplicate primary key, preventing a second copy being attached.
But that understanding must be wrong, because the error is occurring here:
public void Update(MyType updateItem)
{
if (updateItem != null)
{
// debug code, which tells me there is only one match
var foo = Entities.MyTypes.Where(x => x.MyTypeId == updateItem.MyTypeId);
if (Entities.MyTypes.Any(itm => itm.MyTypeId == updateItem.MyTypeId))
{
// error here
Entities.Entry(updateItem).State = System.Data.Entity.EntityState.Modified;
}
else
{
Entities.MyTypes.Add(updateItem);
}
}
}
So that's not trying to add, or re-attach a new object, it's just saying that an existing object is marked as modified, right?
Can someone please explain to me the process here, so I can try and understand and fix the problem?
EDIT: This is the SQL it's trying to run
exec sp_executesql N'SELECT
CASE WHEN ( EXISTS (SELECT
1 AS [C1]
FROM [dbo].[MyType] AS [Extent1]
WHERE [Extent1].[MyTypeId] = @p__linq__0
)) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]',N'@p__linq__0 int',@p__linq__0=4749
Which returns a C1 value of 1. The next entry in the trace is the logger logging the error.