2014-12-02 79 views
1

我在我的應用程序中使用EF 6數據庫模式。我有一個表TBL_USER其中有1:N關係在其他表中。其中之一是TBL_USER_CASETBL_USER的主鍵在TBL_USER_CASE中充當外鍵。使用EF 6中的導航屬性刪除

現在我從TBL_USER刪除一些用戶。在此之前,我需要刪除TBL_USER_CASE中的相應條目。我使用下面的代碼爲

private long DeleteUser(long UserID) 
    { 
     using(VerbaTrackEntities dataContext = new VerbaTrackEntities()) 
     { 
      TBL_USER user = dataContext.TBL_USER.Where(x => x.LNG_USER_ID == UserID).SingleOrDefault(); 
      if(user != null) 
      { 
       foreach (var cases in user.TBL_USER_CASE.ToList()) 
       { 
        user.TBL_USER_CASE.Remove(cases);       
       } 
      } 
      dataContext.SaveChanges(); 
     } 
     return 0; 
    } 

在這裏,我m到處例外

Additional information: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted

我怎麼能這樣做正確操作?

+0

'TBL_USER_CASE'是另一個'1:N'關係的'N'嗎? – Stefan 2014-12-02 07:28:07

+0

@Stefan不,它不是 – 2014-12-02 07:30:49

+0

正常情況下,這個錯誤通常會告訴你問題的細節。這個錯誤描述了你的行爲之後必然存在一些相關的不一致:例如一個沒有匹配的'1'的'1:N'關係。 – Stefan 2014-12-02 07:35:53

回答

0

好的,如果你的目標是刪除用戶,你可以讓框架處理子關係。你可以試試這個:

private long DeleteUser(long UserID) 
{ 
    using(VerbaTrackEntities dataContext = new VerbaTrackEntities()) 
    { 
     TBL_USER user = dataContext.TBL_USER. 
           SingleOrDefault(x => x.LNG_USER_ID == UserID); 
     if(user != null) 
     {  
      dataContext.TBL_USER.Remove(user); 
      dataContext.SaveChanges(); 
     } 
    } 
    return 0; 
} 

更新:你可以試試這個:

private long DeleteUser(long UserID) 
{ 
    using(VerbaTrackEntities dataContext = new VerbaTrackEntities()) 
    { 
     TBL_USER user = dataContext.TBL_USER 
          .SingleOrDefault(x => x.LNG_USER_ID == UserID); 
     if(user != null) 
     { 
      foreach (var cases in user.TBL_USER_CASE.ToList()) 
      { 
       //little modification is here 
       dataContext.TBL_USER_CASE.Remove(cases);       
      } 
     } 
     dataContext.SaveChanges(); 
    } 
    return 0; 
} 
+0

它會不會拋出外鍵違規錯誤? – 2014-12-02 07:53:33

+0

@RajeevKumar:如果您還沒有更改任何「級聯刪除」選項,則它應該刪除與外鍵相關的條目。 – Stefan 2014-12-02 07:55:19

+0

錯誤發生'{「DELETE語句與參考約束」USRCAS_USR_FK \「衝突。數據庫\」VerbaTrack \「,表\」dbo.TBL_USER_CASE \「,列'LNG_USER_ID'發生衝突。\ r \ n聲明已被終止。「} – 2014-12-02 08:39:08

0

我設法通過網絡閱讀這樣做自己。我已通過

System.Data.Entity.Core.Objects.ObjectContext oc = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)dataContext).ObjectContext; 
foreach(var Cases in user.TBL_USER_CASE.ToList()) 
    {       
     oc.DeleteObject(Cases);      
    }      
    oc.SaveChanges(); 
    dataContext.TBL_USER.Remove(user);