[英]Delete using navigation properties in EF 6
I am using EF 6 database modal in my application. 我在应用程序中使用EF 6数据库模态。 I have a table TBL_USER
which has 1:N
relationship in some other table. 我有一个表TBL_USER
在其他一些表中具有1:N
关系。 One of them is TBL_USER_CASE
where primary key of TBL_USER
act as foreign key in TBL_USER_CASE
. 其中之一是TBL_USER_CASE
其中主键TBL_USER
充当外键TBL_USER_CASE
。
Now i am deleting some user from TBL_USER
. 现在我正在从TBL_USER
删除一些用户。 Before that i need to delete corresponding entries in TBL_USER_CASE
. 在此之前,我需要删除TBL_USER_CASE
相应条目。 I am using following code for that 我为此使用以下代码
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;
}
Here im getting exception 我在这里越来越异常
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
How can i do this operation correctly ?? 我如何正确执行此操作?
Ok, if your goal is to delete the user, you can let the framework handle the child-relations. 好的,如果您的目标是删除用户,则可以让框架处理子关系。 You can try this: 您可以尝试以下方法:
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;
}
Update: can you try this one: 更新:您可以尝试以下一种方法:
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;
}
I managed to do so himself by reading through the net. 我自己通过浏览网络做到了这一点。 I have done this by 我已经做到了
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.