gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:18 24 4
gpt4 key购买 nike

  1. 知道 Foo.IdBar.Id 我如何在不从数据库加载实体的情况下创建它们的关系。

    class Foo {
    public int Id { get; set; }
    public Lst<Bar> Bars { get; set; }
    }

    class Bar {
    public int Id { get; set; }
    public Lst<Foo> Foos { get; set; }
    }

    此外,此配置在 DbContext 构造函数中被禁用:

    Configuration.AutoDetectChangesEnabled = false;
    Configuration.ProxyCreationEnabled = false;
    Configuration.LazyLoadingEnabled = false;
  2. 如何解除关系?


例子:

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<Bar>() };
var bar = new Bar { Id = 3, Foos = new List<Foo>() };

// This approach wont work, as AutoDetectChanges are disabled
ctx.Foos.Attach(foo);
ctx.Bars.Attach(bar);

foo.Bars.Add(bar);
ctx.SaveChanges();
}

如何在不更改配置的情况下在这里定义关系。

提前谢谢你。

最佳答案

好的,已经找到解决方案,这里是辅助方法:

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

并在问题示例中使用它:

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<Bar>()};
var bar = new Bar { Id = 3, Foos = new List<Foo>() };

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

关于c# - EF : Create/Remove relation from Many-to-Many relations when `AutoDetectChangesEnabled` and `ProxyCreationEnabled` are disabled on DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39708439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com