【问题标题】:EntityFramework adding nested entities fastEntityFramework 快速添加嵌套实体
【发布时间】:2017-02-03 11:27:11
【问题描述】:

我在数据库中有这些模型。我有一组代表这些模型和关系的 POCO。我需要将它们添加到数据库并创建它们之间的关系。所有对象的数量都像 200k。最有效的方法是什么?

public class A
{
    private ICollection<B> children;

    public A()
    {
        this.children = new HashSet<B>();
    }

    public int Id { get; set; }

    public virtual ICollection<B> Children
    {
        get { return this.children; }
        set { this.children = value; }
    }
}

public class B
{
    private ICollection<C> children;

    public B()
    {
        this.children = new HashSet<C>();
    }

    public int Id { get; set; }

    public int AId { get; set; }

    public virtual A A { get; set; }

    public virtual ICollection<C> Children
    {
        get { return this.children; }
        set { this.children = value; }
    }
}

public class C
{
    private ICollection<D> children;

    public C()
    {
        this.children = new HashSet<D>();
    }

    public int Id { get; set; }

    public int BId { get; set; }

    public virtual B B { get; set; }

    public virtual ICollection<D> Children
    {
        get { return this.children; }
        set { this.children = value; }
    }
}

public class D
{
    private ICollection<E> children;

    public D()
    {
        this.children = new HashSet<E>();
    }

    public int Id { get; set; }

    public int CId { get; set; }

    public virtual C C { get; set; }

    public virtual ICollection<E> Children
    {
        get { return this.children; }
        set { this.children = value; }
    }
}

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

    public int DId { get; set; }

    public virtual D D { get; set; }
}

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    如果您的意思是最快的方法,请使用原始 ADO.NET,甚至考虑使用 SqlBulkCopy。

    您也可以考虑将 TVP 与原始 ADO.NET 一起使用,而不是 BULK COPY

    【讨论】:

    • 我必须使用 EF。我正在尝试让每个“A”添加其所有子代“B”,“B”添加其所有子代“C”,直到层次结构结束,然后当我点击 SaveChanges( ),我收到错误“语句与 FOREIGN KEY 约束 FK_dbo.E_dbo.D_DId 冲突。冲突发生在数据库“TestDatabase”、表“dbo.D”、列“Id”中。”
    • 如果使用 IDENTITY 列,则必须调用 SaveChanges 来获取数据库创建的 Id(并可能将整个内容包装在 DbTransaction 中)
    猜你喜欢
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多