多个模型一个视图和另一个外键

时间:2011-11-15 17:30:20

标签: asp.net-mvc-3 ado.net

我有5个实体,并为其中的三个使用自定义模型,但我需要模型中其他2的外键,自定义模型为

public class CourierRape
{
    public Sender Sender { get; set; }
    public Receiver Receiver { get; set; }
    public Parcel Parcel { get; set; }
}

其余两个实体是CountryCity

控制器如下

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);
        }

但它抛出异常并返回带有外键0的模型

当我删除try catch时会出现以下错误

  

INSERT语句与FOREIGN KEY约束“FK_Receiver_Country”冲突。冲突发生在数据库“452171974654368803C496909AE805A3_ENTS \ VISUAL STUDIO 2010 \ PROJECTS \ COPY OF ECOMMERCECOURIER \ ECOMMERCECOURIER \ APP_DATA \ COURIER.MDF”,表“dbo.Country”,列'Id'。
  声明已经终止。

1 个答案:

答案 0 :(得分:0)

查看您正在创建的对象的CountryId,并确保它们存在于您的国家/地区表格中。