【发布时间】:2015-01-30 08:43:25
【问题描述】:
我在我的应用程序中使用 EF 6 数据库模式。我有一个表TBL_USER,它在其他表中有1:N 关系。其中之一是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
我怎样才能正确地进行这个操作??
【问题讨论】:
-
TBL_USER_CASE是另一个1:N关系的N吗? -
@Stefan 不,不是
-
通常错误会非常详细地显示问题所在。此错误描述在您的操作之后必须存在一些关系不稳定:例如,
1:N关系没有匹配的1。 -
您可能想尝试内部异常以确定导致此问题的字段。如果异常是 DbValidationException 类型,请检查此链接以获取更多详细信息:stackoverflow.com/questions/5345890/…
-
顺便说一句:因为你的函数被称为
DeleteUser;你为什么不删除用户?如果这是您的目标,您可以依靠cascading deletes删除子关系。
标签: c# asp.net entity-framework-6