I'm using vb.net 2013, Entity Framework 6 and SQL Server 2008 R2.
I'm trying to delete from child entities, and this does not work. But if I try to delete directly from context, this works.
In my database I have 2 tables Students
and Result
.
This is my code that does not work :
Dim context as Myentities = New myentities.
Dim s as student.
Dim lresult as new list (of result)
s = context.students.where(Function(t1) t1.value>5).Tolist.first
lresult = (from t in s.results where t.vl2=7 select t).Tolist
for each rs as result in lresult
if rs.vl3=11 then s.results.remove(rs)
Next
Context.SaveChanges
This code produces an error on the last line (context.SaveChanges
) :
An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll
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.
But if I change the line that delete the item, like below, it works :
Dim context as Myentities = New myentities.
Dim s as student.
Dim lresult as new list (of result)
s = context.students.where(Function(t1) t1.value>5).Tolist.first
lresult = (from t in s.results where t.vl2=7 select t).Tolist
for each rs as result in lresult
if rs.vl3=11 then context.results.remove(rs)
Next
Context.SaveChanges
Why does my first snippet of code not work?