EF: Create/Remove relation from Many-to-Many relations when `AutoDetectChangesEnabled` and `ProxyCreationEnabled` are disabled on DbContext

后端 未结 3 1625
情话喂你
情话喂你 2021-01-23 13:19
  1. Knowning Foo.Id and Bar.Id how can I create their relation without loading the entities from the DB.

    class Foo {
        public in         
    
    
            
3条回答
  •  感情败类
    2021-01-23 13:43

    If I'm understanding correctly, you wanted to add Bar object to an existing Foo entity without making a lookup for Foo entity.

    Let say, you have Foo (id = 1) already exists. Wanted to add new Bar (id = 100) entity to it.

    using (var context = new Context())
    {
        var bar = new Bar() { Id = 100 };
        var foo = new Foo() { Id = 1 }; // Only ID is required
    
        context.Foos.Attach(foo);
        bar.Foos.Add(foo);
    
        context.Bars.Add(bar);
        context.SaveChanges();
    }
    

提交回复
热议问题