Reputation: 67
What is the best ( I mean the fastest and simplest) way to inserting data with foreign key?
My models:
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; }
}
I need to create a Package
and some Shipments
in one request (data comes via form). I do it in this way:
[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
}
}
It looks quite odd, but I need create package and many shipments in one action. Moreover I adding new Package
and then I getting it from database - is this the simplest way?
Upvotes: 0
Views: 930
Reputation: 8199
You don't need to use separate repository for master and detail tables. Map you view models fields to master and detail entities and call master Add method only it will keep track of children itself. If PackId is autonumber then you don't need to do any thing. if it is not assign primary key of pkgid to foreign key of shipment
var _Package = new Package();
// Assign fields of packages from viewmdoel to entity
foreach(var item in form.shipments)
{
var _Shipment = new Shipment();
//Assign shipment fields from your view models to shipment entity
_Package.shipments.Add(_Shipment)
}
using (var dbCtx = new yourDBEntities())
{
//add package entity into entitySet
dbCtx.Package.Add(_Package);
//Save whole entity graph to the database
dbCtx.SaveChanges();
}
or you call you repo method from package for add/Save
You can see a simple tutorial here
Upvotes: 1