实体框架-避免子副本,如果他们还没有被持久化

本文关键字:他们 如果 还没有 持久化 副本 框架 实体 | 更新日期: 2023-09-27 18:03:17

实际上我使用DbContext,但我只是测试了它与ObjectContext。

// Engine 1
Engine engine = new Engine();
Manufacturer manufacturer = new Manufacturer();
engine.Manufacturer = manufacturer;
// Engine 2
engine = new Engine();
engine.Manufacturer = manufacturer // Engine 2 has the same manufacturer like Engine 1
context.SaveChanges();

我使用标识列(int),其中生成新的id。在调试模式下,我看到引擎的ID为"0"。如果我实现context。SaveChanges就在Engine 1块之后,新的制造商被保存到DB。使用EntityKey或Any检查,我可以将新制造商引用到引擎2而不会出现任何问题。但是没有立即SaveChanges(),同一制造商的两个条目被保存到DB(上面的代码)。EF不能像普通对象一样在内部引用吗?正如你在上面看到的,制造商是同一个对象,所以我想知道是否有可能在不预先保存子/制造商的情况下获得成功的插入。

我想我找到问题了

MachineEntities context = new MachineEntities();
        context.Configuration.AutoDetectChangesEnabled = true;
        // Engine 1
        Engine engine1 = new Engine();
        engine1.Name = "engine1";
        Manufacturer manufacturer = new Manufacturer();
        manufacturer.Name = "manufacturer1";
        engine1.Manufacturer = manufacturer;
        // Engine 2
        Engine engine2 = new Engine();
        engine2.Name = "engine2";
        manufacturer = new Manufacturer();
        manufacturer.Name = "manufacturer1";
        engine2.Manufacturer = manufacturer;

        // Add Engine 1
        if (context.Manufacturers.Any(m => m.Name == engine1.Manufacturer.Name))
        {
            // The manufacturer's name is identical, so use the one in the context instead the assigned one.
            engine1.Manufacturer = context.Manufacturers.Single(m => m.Name == engine1.Manufacturer.Name);
        }
        else
        {
            // The manufacturer is not known, add it to the context
            context.Set<Manufacturer>().Add(engine1.Manufacturer);
        }
        // Add Engine 2

        if (context.Manufacturers.Any(m => m.Name == engine1.Manufacturer.Name))
        {
            // The manufacturer's name is identical, so use the one in the context instead the assigned one.
            engine2.Manufacturer = context.Manufacturers.Single(m => m.Name == engine2.Manufacturer.Name);
        }
        else
        {
            context.Manufacturers.Add(engine2.Manufacturer);
        }
        context.SaveChanges();
        context.Dispose();

"Any"或任何比较都不会给我任何结果。它只给我那些实体,这些实体已经持久化在DB中,而不是新添加的实体。所以它是重复的。正如我在调试器中看到的那样,本地的被忽略了,而"结果视图"中的一个是命令被执行的地方。所以新添加的实体位于"Manufacturers.Local"

实体框架-避免子副本,如果他们还没有被持久化

我刚刚尝试了以下内容:

var a1 = new Activity{WorkflowId = 1, Title = "test"};
var a2 = new Activity{WorkflowId = 1, Title = "test2"};
var d = new WorkflowDisplay{WorkflowId = 1, Title = "Test"};
a1.WorkflowDisplay = d;
a2.WorkflowDisplay = d;
// Any of the next three lines can be commented out, but if
// they are all commented, nothing happens.
AddToWorkflowDisplays(d);
AddToActivities(a1);
AddToActivities(a2);
SaveChanges();

…我只看到加了一个WorkflowDisplay。我很确定这和你的具体实现有关。您是否覆盖了任何实体的GetHashCodeEquals方法,或者对自动生成的代码进行了任何类似的自定义?