Snahider
Snahider

Reputation: 188

How to remove an Entity from a Collection without load all collection data

The Code-First model:

public class Princess
{
    public int Id { get; set; }
    public virtual ICollection<Unicorn> Unicorns { get; set; }
}

public class Unicorn
{
    public int Id { get; set; }
    public virtual ICollection<Princess> Princesses { get; set; }
}

is it possible to remove an entity from the collection without load (eager or lazy) all the collection data?

var princess = context.Princesses.Where(x => x.Id == 1).Single();
var unicorn = context.Unicorns.Where(x => x.Id == 1).Single();
princes.Unicorns.remove(unicorn); //load all assigned unicorns
context.SaveChanges();

I guess the ExecuteSqlCommand should work. Other solution?

Upvotes: 2

Views: 305

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126547

Use stubs. Off the top of my head (may require tweaks):

var princess = new Princess { Id = 1 };
princess.Unicorns.Add(new Unicorn { Id = 1 });
context.Princesses.Attach(princess);  // start tracking changes
princes.Unicorns.Remove(unicorn);
context.SaveChanges();

Upvotes: 1

Related Questions