【发布时间】:2021-09-17 11:02:42
【问题描述】:
用外键插入数据最好(我的意思是最快和最简单)的方法是什么?
我的模型:
public class Package
{
public Int PackId { get; set; }
// some fields
// list with other models!
public ICollection<Shipment> shipments { get; set; }
}
public class Shipment
{
Int Id { get; set; }
// some fields
[ForeignKey]
Int PackId { get; set; }
Package package { get; set; }
}
我需要在一个请求中创建一个Package 和一些Shipments(数据来自表单)。我是这样做的:
[HttpPost]
public void ControllerMethod(MyViewModel form)
{
transaction
{
// empty list,method from
var pack_id = _packageRepository(some_fields_here, new List<Shipment>());
// repo returns id
var package = _packageRepository.GetSpecific(pack_id);
var ls_shipments = new List<Shipment>();
foreach(var x in form.ListOfShipments)
{
var ship = _shipRepository.Add(some_fields_here, pack_id, package);
ls_shipments.Add(ship);
}
// replace empty list with list filled in foreach above
package.shipments = ls_shipments;
_context.SaveChanges();
}
catch (Exception e)
{
// some actions here
}
}
看起来很奇怪,但我需要一次创建包裹和许多货物。此外,我添加了新的Package,然后从数据库中获取它——这是最简单的方法吗?
【问题讨论】:
标签: c# entity-framework-core asp.net-core-mvc