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();
}
The solution I am using is to get the DbEntityEntry
for the entity and manually marking it as deleted.
using (var db = new Context()) {
var post = db.LogPosts.First(p => p.ID == postID);
var reply = post.Replies.First(r => r.ID == replyID);
db.Entry(reply).State = System.Data.Entity.EntityState.Deleted;
db.SaveChanges();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.