2014-12-02 34 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);