本文介绍了EF:在 DbContext 上禁用“AutoDetectChangesEnabled"和“ProxyCreationEnabled"时从多对多关系创建/删除关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
知道
Foo.Id
和Bar.Id
如何在不从数据库加载实体的情况下创建它们的关系.
Knowning
Foo.Id
andBar.Id
how can I create their relation without loading the entities from the DB.
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
构造函数中也被禁用:
Also this configuration are disabled in DbContext
constructor:
Configuration.AutoDetectChangesEnabled = false;
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
以及如何消除这种关系?
And how it is possible to remove the relationship?
<小时>
例子:
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();
}
如何在不更改配置的情况下在这里定义关系.
How can I define relation here, without changing the configuration.
提前谢谢你.
推荐答案
好的,找到了解决方案,这里是辅助方法:
Ok, have found the solution and here is the helper method:
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
);
}
并在我的问题示例中使用它:
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<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();
}
这篇关于EF:在 DbContext 上禁用“AutoDetectChangesEnabled"和“ProxyCreationEnabled"时从多对多关系创建/删除关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!