I am using Entity Framework 4.3.1 in a project, using code and the DbContext API first. My application is an n-tier application in which disconnected objects can come from the client. I am using SQL Server 2008 R2, but will move on to SQL Azure soon. I am facing a problem that I just cannot solve.
Imagine that I have several classes:
class A {
}
class B {
public A MyA { get; set; }
}
class C {
public A MyA { get; set; }
}
By default, EF works with object graphs. For example, if I have an instance of B that encapsulates an instance of A and I call it myDbSet.Add(myB);, it will also mark the instance of A as added (if it is not already monitored).
, , , . :
A myA = new A();
C myC = new C() {
A = myA;
}
B myB0 = new B() {
A = myA;
}
B myB1 = new B() {
A = myA;
}
myDbSetC.Attach(myC);
context.Entry(myC).State = Modified;
myDbSetB.Add(myB0);
myDbSetB.Add(myB1);
context.SaveChanges();
AcceptChanges cannot continue because the object key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges. , , add myB0 A , A, .
- call myDbSet.AddOnly(myB), , , .
:
# 1:
-, , myA .
private void MarkGraphAsUnchanged<TEntity>(TEntity entity) where TEntity : class {
DbEntityEntry entryForThis = this.context.Entry<TEntity>(entity);
IEnumerable<DbEntityEntry> entriesItWantsToChange = this.context.ChangeTracker.Entries().Distinct();
foreach (DbEntityEntry entry in entriesItWantsToChange) {
if (!entryForThis.Equals(entry)) {
entry.State = System.Data.EntityState.Unchanged;
}
}
}
...
myDbSetB.Add(myB0);
MarkGraphAsUnchanged(myB0);
myA, - ObjectStateManager.
# 2:
, , "" " ". , myB0.A = null, .
# 3:
TransactionScope DbContext. SaveChanges() Attach() Add(), , , # 1.
# 4:
TransactionScope, , /DAO DbContext SaveChanges() , . " , ". SQL Profiler , SaveChanges() , ( Add()), UPDATE SQL - doesn 't . Entity Framework .
# 5:
TransactionScope DbTransaction. - , EntityConnection , ( EntityConnection, ). , , , , , . dev , , Attach() ( - - ).
!! , , , DAO INSERT, UPDATE DELETE, . , Entity Framework O/R, !