简体   繁体   English

实体框架:子表中的记录未插入

[英]Entity Framework: records in child table are not inserting

Records in parent table are saving successfully but child table records are not saving and no error is coming, using Entity Framework with repository pattern available here .父表中的记录保存成功,但子表记录未保存且不会出现错误,使用具有可用存储库模式的实体框架here

Below is the sample schema design of my tables, might be a special case.下面是我的表的示例架构设计,可能是一个特例。

在此处输入图片说明

Considering above tables if I try to insert records in Table2 and Table3 together no record inserted into Table3.考虑上面的表格,如果我尝试将 Table2 和 Table3 中的记录一起插入,则没有记录插入到 Table3 中。

Please let me know if need further clarification on the question.如果需要进一步澄清这个问题,请告诉我。

Thanks in advance!!提前致谢!!

EDIT 1编辑 1

Below is the code I am using to insert parent and child records together.下面是我用来插入父和子记录的代码。

    var parent = new Table2()
    {
        Table1Id = 1,
        SecondColumn = 1
    };

    parent.Tables3.Add(new Table3()
    {
        Table1Id = 1,
        SecondColumn = 1,
        AnotherColumn = 1
    });

    context.Set<Table2>().Attach(parent);
    context.Entry<Table2>(parent).State = EntityState.Added;
    context.SaveChanges();

EDIT 2编辑 2

public partial class Table2
{
    public Table2()
    {
        this.Tables3 = new HashSet<Table3>();
    }

    public int Table1Id { get; set; }
    public int SecondColumn { get; set; }

    public virtual ICollection<Table3> Tables3 { get; set; }
}

public partial class Table3
{
    public int Table1Id { get; set; }
    public int SecondColumn { get; set; }
    public int AnotherColumn { get; set; }
}

You should do one of two:您应该执行以下两项操作之一:

  1. Use add instead of attach使用添加而不是附加

    var parent = new Table2() { Table1Id = 1, SecondColumn = 1 }; parent.Tables3.Add(new Table3() { Table1Id = 1, SecondColumn = 1, AnotherColumn = 1 }); context.Set<Table2>().Add(parent); context.SaveChanges();

In this case all navigation properties will also be added.在这种情况下,还将添加所有导航属性。

  1. Paint your whole graph with state after attach (now you set state only to parent table).附加后用状态绘制整个图形(现在您仅将状态设置为父表)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM