Reputation: 789
I have used EF to generate classes for my database tables:
public partial class Course
{
public Course()
{
this.People = new HashSet<People>();
}
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Person> People { get; private set; }
}
public partial class Person
{
public int ID { get; set; }
public string Name { get; set; }
public virtual Course Course { get; set; }
}
As you can see each course has a collection of people. I created a second partial class so my code does not get cleared when i refresh the EF diagram. My question is how can i clear the list of people from within the course object?
I tried:
public partial class Course
{
public void ResetCourse()
{
this.People.Clear();
}
}
But i get this error:
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.
which is apparently caused because EF is not actually deleting the person object just removing the relationship between the two which SQL throws out because it cannot have a null key.
Apparently i should use something like context.DeleteObject(person)
However inside the course object it has no reference to the context and i wanted to keep the code inside the object to keep it simple of the ui code.
Upvotes: 1
Views: 892
Reputation: 14919
Instead of using Course classes to manage database operations; it is better to employ repository and unitofwork patterns while working with entity framework. Otherwise, your entities always carries context on them; which will lead to some problems.
Just create a Course repository with context as a parameter and employ the database operations in the repository instead of the entity itself. Refer to: Unit of Work and repository patterns
Upvotes: 1