Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete an entity when I have no DbSet for that type?

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?

like image 966
Rob Church Avatar asked Dec 08 '25 20:12

Rob Church


1 Answers

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();
}
like image 69
Lukazoid Avatar answered Dec 11 '25 08:12

Lukazoid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!