I am using EF 6 database modal in my application. I have a table TBL_USER
which has 1:N
relationship in some other table. One of them is TBL_USER_CASE
where primary key of TBL_USER
act as foreign key in TBL_USER_CASE
.
Now i am deleting some user from TBL_USER
. Before that i need to delete corresponding entries in 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.