Skip to content

Commit ae4ea40

Browse files
author
Jeff Treuting
committed
Added try/catch to the new EF UpdateItem context stuff
1 parent 81a60de commit ae4ea40

1 file changed

Lines changed: 19 additions & 12 deletions

File tree

SharpRepository.Ef5Repository/Ef5RepositoryBase.cs

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -50,24 +50,31 @@ protected override void UpdateItem(T entity)
5050
{
5151
var entry = Context.Entry<T>(entity);
5252

53-
if (entry.State == EntityState.Detached)
53+
try
5454
{
55-
TKey key;
56-
57-
if (GetPrimaryKey(entity, out key))
55+
if (entry.State == EntityState.Detached)
5856
{
59-
// check to see if this item is already attached
60-
// if it is then we need to copy the values to the attached value instead of changing the State to modified since it will throw a duplicate key exception
61-
// specifically: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."
62-
var attachedEntity = Context.Set<T>().Find(key);
63-
if (attachedEntity != null)
64-
{
65-
Context.Entry(attachedEntity).CurrentValues.SetValues(entity);
57+
TKey key;
6658

67-
return;
59+
if (GetPrimaryKey(entity, out key))
60+
{
61+
// check to see if this item is already attached
62+
// if it is then we need to copy the values to the attached value instead of changing the State to modified since it will throw a duplicate key exception
63+
// specifically: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."
64+
var attachedEntity = Context.Set<T>().Find(key);
65+
if (attachedEntity != null)
66+
{
67+
Context.Entry(attachedEntity).CurrentValues.SetValues(entity);
68+
69+
return;
70+
}
6871
}
6972
}
7073
}
74+
catch (Exception e)
75+
{
76+
// ignore and try the default behavior
77+
}
7178

7279
// default
7380
entry.State = EntityState.Modified;

0 commit comments

Comments
 (0)