gpt4 book ai didi

c# - Entity Framework 4.1 RTW 代码优先 - POCO 一对多是否需要引用子实体和子实体主键?

转载 作者:行者123 更新时间:2023-11-30 22:39:26 25 4
gpt4 key购买 nike

如果您有一个父类和一个子类,映射实体的最佳模式是什么。

我看到过很多建议,其中父类同时引用了子类和子类 ID。例如

public class Parent
{
public int Id
{
get;
set;
}

public int ChildId
{
get;
set;
}

public virtual Child Child
{
get;
set;
}
}

public class Child
{
public int Id
{
get;
set;
}
}

public class ParentMapping : EntityTypeConfiguration<Parent>
{
public ParentMapping()
{
HasKey(x => x.Id);

HasRequired(X => x.Child)
.WithMany()
.Map(x => x.ToTable("Parent")
.MapKey("ChildId"));
}
}

使用这种模式,在保存父项时,如果您想将子项换成另一个但已存在的子项,我看到的示例只是更新 ChildId 而不是感觉不对的 Child,因为该对象与自身不同步。

代码在没有 ChildId 的情况下看起来更整洁,但使用这种模式时,我无法使用现有的子项保存父项,因为 EF 正在尝试保存新的子项。

public class Parent
{
public int Id
{
get;
set;
}

public virtual Child Child
{
get;
set;
}
}

最好的模式是什么,我想知道是否需要 ChildId,然后 Child 属性如何保持同步,是否会从数据库中延迟加载。

最佳答案

这是foreign key and independent association之间的区别.使用外键关联时,您实际上可以只使用键而无需加载相关对象。如果您加载了引用,它会使引用不同步——但情况并非总是如此。如果您想保持引用同步,您几乎又回到了必须通过独立关联解决的情况。

如果你公开外键,你应该使用它,因为它使很多事情变得更容易。如果你使用独立协会,你应该这样做:

var parent = GetUpdatedParentSomehow();
// Dummy object for the old child if the relation is not loaded
parent.Child = new Child { Id = oldChildId };
// Attach the parent
context.Parents.Attach(parent);

// Create dummy for new child (you can also load a child from DB)
var child = new Child { ID = newChildId };
// No attach the child to the context so the context
// doesn't track it as a new child
context.Childs.Attach(child);
// Set a new child
parent.Child = child;
// Set parent as modified
context.Entry(parent).State = EntityState.Modified;
context.SaveChanges();

有一个非常奇怪的部分,我正在为老 child 创建假人。我几乎可以肯定,如果我在附加父项并设置新子项之前不这样做,我将在保存更改期间遇到一些异常(在独立关联的情况下)。

关于c# - Entity Framework 4.1 RTW 代码优先 - POCO 一对多是否需要引用子实体和子实体主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5714800/

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