使用EF同时保存父对象及其子对象(具有父对象的外键)的列表

时间:2016-08-12 18:56:29

标签: c# entity-framework entity-framework-core

以下代码会自动将销售订单保存到SalesOrder表,将销售订单明细自动保存到SalesOrderDetail表吗?

我的目标是能够创建我的主要权利列表,并使用它的导航属性创建另一个列表并一次性保存。

请参阅以下内容:

 ? a d | A u n   Z h i   G i e | J a l a n   K e p o n g | 5 2 1 0 0 | 1 . 0    0 | C 1 2 3 java.lang.NumberFormatException: For input string: "a"
at         java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.lang.Integer.parseInt(Integer.java:580)
  at java.lang.Integer.parseInt(Integer.java:615)
  at ReadWriteFile.readFile(patron.java:50)
  at Main.main(Testingprogram.java:6)
或者我将不得不做类似的事情:

List<SalesOrder> salesOrders = new List<SalesOrder>()
{
    new SalesOrder()
    {
        OrderDate = DateTime.Now,
        OrderDetails = new List<SalesOrderDetail>()
        {
            new SalesOrderDetail() { ItemId = 1 },
            new SalesOrderDetail() { ItemId = 2 },
            new SalesOrderDetail() { ItemId = 3 }
        }
    },
    new SalesOrder()
    {
        OrderDate = DateTime.Now,
        OrderDetails = new List<SalesOrderDetail>()
        {
            new SalesOrderDetail() { ItemId = 1 },
            new SalesOrderDetail() { ItemId = 2 }
        }
    }
};

_context.SalesOrders.AddRange(salesOrders);
_context.SaveChanges();

1 个答案:

答案 0 :(得分:1)

我使用的是Entity Framework Core 1.0(EF7),以下功能完美无缺。请注意我的模型的设置方式:

    public class SalesOrder 
    {
        public int Id {get; set;}
        public DateTime OrderDate {get; set;}
        // Nav property
        public ICollection<SalesOrderDetail> OrderDetails { get; set; }
    }

    public class SalesOrderDetail
    {
        public int Id {get; set;}
        // Foreign key property
        public int SalesOrderId {get; set;}
        // Nav property
        public SalesOrder SalesOrder {get; set;}
    }

只需执行以下操作并自动保存正确的外键值,而无需指定它们:

List<SalesOrder> salesOrders = new List<SalesOrder>()
{
    new SalesOrder()
    {
        OrderDate = DateTime.Now,
        OrderDetails = new List<SalesOrderDetail>()
        {
            new SalesOrderDetail() { ItemId = 1 },
            new SalesOrderDetail() { ItemId = 2 },
            new SalesOrderDetail() { ItemId = 3 }
        }
    },
    new SalesOrder()
    {
        OrderDate = DateTime.Now,
        OrderDetails = new List<SalesOrderDetail>()
        {
            new SalesOrderDetail() { ItemId = 1 },
            new SalesOrderDetail() { ItemId = 2 }
        }
    }
};

_context.SalesOrders.AddRange(salesOrders);
_context.SaveChanges();

是的,导航属性不仅有助于在检索数据时使用Include,还可以使保存更轻松!