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

我看到了很多建议,其中父级同时引用了子类和子类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();


我为大孩子创建虚拟对象时有一个非常奇怪的部分。我几乎可以确定,如果在附加父级和设置新的子级之前不这样做,那么在保存更改时(如果是独立关联)我会得到一些例外。

09-26 12:50