首页 > 解决方案 > EF6 数据库优先:如何将数据保存到集合导航属性?

问题描述

我是 Entity Framework 的新手,我正在使用 db first 模型,我正在尝试存储一些数据。我有一个与另一个表 (table2) 相关的表 (table1),因此 EF 在两者之间创建了一个导航属性。我是在 table1 中设置导航属性,还是添加一个新实体以插入 table2,记录 id 为 table1?Table2 有一个指向 Table1 的 id 字段的外键。我需要 table2 来填充它。另外据我了解, id 字段将由 EF 设置为增量 int 值吗?

public partial class Table1
{
    public int Id1 {get; set;}
    public virtual ICollection<Table2> Table2s {get; set;}
}


public partial class Table2
{
    public int Id2 {get; set;}
    public int somedata {get; set;}
    public int Id1 {get; set;}
    public virtual Table1 Table1 {get; set;}
}


using(TablesEntities context = new TablesEntities())
{
    var data = new Table1 
    {
        Table2s = new [] { new Table2s
        {
            somedata = 123,
            id1 = ???
        }}
    }
}

标签: c#entity-framework-6

解决方案


推荐阅读