I have the following domain model:
public class Campaign
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Content> Content { get; set; }
}
public class Content
{
public virtual long Id { get; set; }
public virtual string Body { get; set; }
}
This is configured:
modelBuilder.Entity<Campaign>().HasMany(x => x.Content).WithOptional();
In my service I have the following code:
Campaign campaign = campaignRepository.GetById(id);
This loads the campaign and any associated content items into the collecti开发者_高级运维on which is great. The issue comes with the following code:
campaign.Name = "new value";
campaign.Content.Clear();
unitOfWork.Commit();
This does not delete the content rows from the database. It actually sets the foreign key in the content table to null for the affected rows but it does not delete the rows.
I then tried to modify the configuration to:
modelBuilder.Entity<Campaign>().HasMany(x => x.Content).WithRequired();
This would simply give me the following exception: A relationship from the 'Campaign_Content' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Campaign_Content_Target' must also in the 'Deleted' state.
There must be a way to delete rows from the content collection. I must be missing something. Any help is appreciated.
You will have call the Remove method on the corresponding DbSet for each entity instance.
foreach(var content in campaign.Content)
{
dbContext.Contents.Remove(content);
}
精彩评论