我在我的应用程序中使用了EF 6数据库模式。我有一个在其他表中有1:N关系的表TBL_USER。其中之一是TBL_USER_CASE,其中TBL_USER的主键在TBL_USER_CASE中充当外键。
现在我正在从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;
}在这里,我得到了异常
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
如何才能正确执行此操作??
发布于 2014-12-02 15:50:14
好的,如果你的目标是删除用户,你可以让框架来处理子关系。您可以尝试这样做:
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;
}发布于 2014-12-02 17:17:52
我自己通过网络阅读做到了这一点。我已经做到了这一点
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);https://stackoverflow.com/questions/27243725
复制相似问题