I am using a DbContext that has been provided and I cannot change it.
Edited for brevity, the context contains two types
public class LogPost {
public int ID { get; set; }
public string Comment { get; set; }
public virtual ICollection<LogReply> Replies { get; set; }
public LogPost() {
Replies = new List<LogReply>();
}
}
public class LogReply {
public int ID { get; set; }
public string Comment { get; set; }
}
There is no DbSet<LogReply> to work with, only a DbSet<LogPost>. If I try removing the reply from the post.Replies collection, it throws an exception about foreign key properties not being null (as expected).
How can I delete a reply?
I know you are unable to change the existing DbContext implementation, but the method to create a DbSet<T> for a DbContext is public (see here).
So you could try the following:
using(var db = new Context())
{
var post = db.LogPosts.First(p => p.ID == postID);
var reply = post.Replies.First(r => r.ID == replyID);
var logReplies = db.Set<LogReply>();
logReplies.Remove(reply);
db.SaveChanges();
}
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