2011-03-04 48 views
0

我正在處理MVC3應用程序,並使用DbContext代碼生成器從我的數據庫中創建了POCO類。一切都很好,直到我陷入這種情況。請注意,我使用存儲庫模式,併爲每個實體使用專用存儲庫,以獲取DbContext的新實例。現在如何保存來自不同的相關新對象DBContext CTP5

,我在這樣的情況:

對象A的關係,一到許多與B(A可以有一個或多個B) 對象B有很多一對一的關係與C(C可有一個或多個B) 對象B有很多一對一的關係與d(d可以有一個或多個B)

我要補充一個新的對象B,考慮到對象C和d現在還沒有,所以我只能做關係,可以創建或更新對象A.具體考慮A是客戶,B是訂閱(C和D是B中的虛擬對象屬性)。

現在如果我嘗試保存,我在C和D表中有重複項,而對象的管理似乎工作。 所以,我鑫卡特,我應該脫離實體做的關係前,但是當我打電話調用SaveChanges()我得到這個錯誤:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

下面的代碼:

 

Customer customer = customerRepository.Get(ID);     
if (customer == null) 
{ 
    customer = new Customer(); 
    customer.Email = Request.Form["Email"].ToString(); 
} 

Subscription subscription = new Subscription(); 
subscription.Active = true; 
subscription.DateSubscription = DateTime.Today; 

Object C = objectCRepository.Get(Request.Form["IDObjectC"]);//Get C object from database 
Object D = objectDRepository.Get(Request.Form["IDObjectD"]);//Get D object from database 

if (C != null) 
{ 
    //I tried also to detach the objects before adding to subscription 
    subscription.C = C; 
    subscription.D = D; 
    customer.Subscriptions.Add(subscription); 

    if (customer.IDCustomer == 0) 
     customerRepository.Add(customer); 
    else 
     UpdateModel(customer); 

    customerRepository.Save(); 
} 
 

而這裏添加和保存客戶資料庫的方法:

 

public override void Add(Cliente cliente) 
{ 
    db.Cliente.Add(cliente); 
} 

public override void Save() 
{ 
    foreach (var entry in db.ChangeTracker.Entries() 
       .Where(e => e.State == EntityState.Modified || e.State == EntityState.Added   || e.State == EntityState.Unchanged || e.State == EntityState.Detached)) 
    { 
    string state = ObjectContext.GetObjectType(entry.Entity.GetType()).Name + " " + entry.State.ToString(); 

    if (ObjectContext.GetObjectType(entry.Entity.GetType()).Name.Equals("C") || ObjectContext.GetObjectType(entry.Entity.GetType()).Name.Equals("D")) 
    { 
    entry.State = EntityState.Unchanged; 
    } 
    dbContext.SaveChanges(); 
} 
 

我試圖也用這個對象C和D.

 

((System.Data.Entity.Infrastructure.IObjectContextAdapter)dbContext).ObjectContext.Refresh(System.Data.Objects.RefreshMode.StoreWins, entry); 
 

而收到的錯誤是

The element at index 0 in the collection of objects to refresh has a null EntityKey property value or is not attached to this ObjectStateManager.

我注意到,在CTP5添加的選項AsNoTracking(),我試圖使用它,但沒有! 我還檢查了操作中涉及的每個屬性的併發模式,並將所有屬性設置爲無。 我完成的想法:(!

任何幫助將不勝感激!謝謝!

回答

0

其實我自己使用的加載AsNoTracking()方法,節省了實體之前,我改變狀態不變解決。

 
//On loading 
Context.Object.AsNoTracking().SingleOrDefault(l => l.Property == Property); 

//On saving 
Object.State = EntityState.Unchanged; 
Object.SaveChanges(); 

希望這可以幫助別人