I have 5 entity and use the custom model for the three of them but I need the foreign key of other 2 in the model the custom model are as
public class CourierRape
{
public Sender Sender { get; set; }
public Receiver Receiver { get; set; }
public Parcel Parcel { get; set; }
}
The two remaining entities are Country and City
The controller is as follows
public ActionResult Create()
{
ViewBag.S_City_Id = new SelectList(db.Cities, "Id", "Name");
ViewBag.S_Country_Id = new SelectList(db.Countries, "Id", "Name");
ViewBag.R_City_Id = new SelectList(db.Cities, "Id", "Name");
ViewBag.R_Country_Id = new SelectList(db.Countries, "Id", "Name");
return View();
}
//
// POST: /Courier/Create
[HttpPost]
public ActionResult Create(CourierRape c)
{
ViewBag.S_City_Id = new SelectList(db.Cities, "Id", "Name", c.Sender.S_City_Id);
ViewBag.S_Country_Id = new SelectList(db.Countries, "Id", "Name", c.Sender.S_Country_Id);
ViewBag.R_City_Id = new SelectList(db.Cities, "Id", "Name", c.Receiver.R_City_Id);
ViewBag.R_Country_Id = new SelectList(db.Countries, "Id", "Name", c.Receiver.R_Country_Id);
try
{
SenderController s = new SenderController();
ReceiverController r = new ReceiverController();
ParcelController p = new ParcelController();
r.Create(c.Receiver);
s.Create(c.Sender);
c.Parcel.Sender_Id = c.Sender.Id;
c.Parcel.Receiver_Id = c.Receiver.Id;
p.Create(c.Parcel);
return RedirectToAction("Index");
}
catch
{
ViewBag.Message = c.Sender.S_City_Id.ToString() +" " + c.Receiver.R_City_Id.ToString() + " " + c.Receiver.R_Country_Id.ToString() + " "+ c.Sender.S_Country_Id.ToString();
return View(c);
}
but it throws the exception and return the model with the 0 of the foreign keys
And when I remove the try catch it gives the following error
The INSERT statement conflicted with the FOREIGN KEY constraint “FK_Receiver_Country”. The conflict occurred in database “452171974654368803C496909AE805A3_ENTS\VISUAL STUDIO 2010\PROJECTS\COPY OF ECOMMERCECOURIER\ECOMMERCECOURIER\APP_DATA\COURIER.MDF”, table “dbo.Country”, column ‘Id’.
The statement has been terminated.
Look at the CountryId on the objects you’re creating and make sure they exist in your country table.