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

后端 未结 3 1616
情话喂你
情话喂你 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 14:00

    Ok, have found the solution and here is the helper method:

    static void ChangeRelationship(
        IObjectContextAdapter ctx, 
        T1 a, 
        T2 b, 
        Expression> getNavigationProperty,
        EntityState state) where T1: class
    {
        ctx
            .ObjectContext
            .ObjectStateManager
            .ChangeRelationshipState(
                a,
                b,
                getNavigationProperty,
                state
            );
    }
    

    And using it in my example from the question:

    using (var ctx = new DbCtx())
    {
        ctx.Configuration.LazyLoadingEnabled = false;
        ctx.Configuration.ProxyCreationEnabled = false;
        ctx.Configuration.AutoDetectChangesEnabled = false;
        ctx.Database.Log += Console.WriteLine;
    
        var foo = new Foo {Id = 1, Bars = new List()};
        var bar = new Bar { Id = 3, Foos = new List() };
    
        ctx.Entry(foo).State = EntityState.Unchanged;
        ctx.Entry(bar).State = EntityState.Unchanged;
    
        // create
        ChangeRelationship(ctx, foo, bar, x => x.Bars, EntityState.Added);
        ctx.SaveChanges();
    
        // remove
        ChangeRelationship(ctx, foo, bar, x => x.Bars, EntityState.Deleted);
        ctx.SaveChanges();
    }
    

提交回复
热议问题