开发者

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

开发者 https://www.devze.com 2023-03-05 05:53 出处:网络
The Code-First model: public class Princess { public int Id { get; set; } public virtual ICollection<Unicorn> Unicorns { get; set; }

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?


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消