I am making code first entity framework database model, and I am struggeling with cascade delete. There are my simple classes:
public class User {
[Key()]
public int Id {get; set;}
public string Name {get; set;}
public int CampaignId {get; set;}
[ForeignKey("CampaignId")]
public virtual Campaign Campaign {get; set;}
}
public class Campaign {
[Key()]
public int Id {get; set;}
public string Description {get; set;}
public virtual List<User> Users {get; set;}
public Campaign() {
Users = new List<User>();
}
}
The basic idea is to assign one campaign to every user. When I delete campaign which is assigned by user:
internal static void DeleteCampaign(Campaign campaignToDelete) {
using (var context = new DatabaseContext()) {
context.Entry(campaignToDelete).State = EntityState.Deleted;
context.SaveChanges();
}
}
Users assigned to that campaign are deleted too. What I want is to not delete users, but assign them to first avaible campaign, or null. For some reason I cant do something like that:
internal static void DeleteCampaign(Campaign campaignToDelete) {
using (var context = new DatabaseContext()) {
for (int i = 0; i < campaignToDelete.Users.Count; i++) {
campaignToDelete.Users[i].Campaign = context.Campaigns.ElementAt(0);
}
context.Entry(campaignToDelete).State = System.Data.Entity.EntityState.Deleted;
context.SaveChanges();
}
}
Because I am getting error:
An unhandled exception of type 'System.ObjectDisposedException' occurred in EntityFramework.dll
Additional information: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
So how can I avoid that?