I am trying to remove an object from a collection in entity framework, but unfortunately my code is failing. I would be grateful if you could have a look and let me know if you can figure out what I'm doing wrong. My objects are as follows:
Adding and editing entries works absolutely fine.
However, when I try to remove a Badge from a Person using the code below, it doesn't work:
Postback event handler on example.aspx
****The person object has been loaded as part of the load event on the page****
Badge badge = BadgeHelper.getBadge(badgeID);
if (command == "Delete")
{
PersonHelper.removeBadgeFromPerson(badge, person);
}
Delete method on PersonHelper class (wrapper for all processing)
person.Badges.Remove(badge);
DbContext.SaveChanges();
The Remove(badge) returns false and I cannot profile this as I am using SQL Compact 4.0
Thanks in advance for your help!
This was actually resolved in one of the MSDN forums. The full details can be found on the link here
However, as a summary, to use the Remove() method, both collections in the many to many relationship need to be loaded before any changes take place. The code sample is attached below:
class Program {
static void Main(string[] args)
{
using (var context= new MyContext())
{
var post1 = context.Posts.Find(3);
var tag1 = context.Tags.Find(2);
context.Entry(post1).Collection("Tags").Load();
post1.Tags.Remove(tag1);
context.SaveChanges();
}
}
}
public class Post
{
public int PostId { get; set; }
public string PostContext { get; set; }
public ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int TagId { get; set; }
public string TagContext { get; set; }
public ICollection<Post> Posts { get; set; }
}
public class MyContext:DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
}
I hope that this helps somebody else with similar issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With