简体   繁体   中英

How to insert data into multiple tables in ASP. NET MVC. Entity Framework

I have two tables tblProduct & tblImages . tblImages will have multiple images for a product and has a foreign key related to tblProduct . I have a problem with inserting data into multiple tables.

This is my view code:

<!-- Text Boxes and dropdown lists for tblProduct above and below is for adding files to tblImages-->
<div class="col-md-10">
    <input multiple type="file" id="file" name="file" />
</div>

and here is my controller's code:

public ActionResult AddProduct_Post([Bind(Include = "productName, productDescription, productPrice, productCategory")]tblProduct tblProduct,List<HttpPostedFileBase> file)
{
    List<tblImage> prodImages = new List<tblImage>();
    var path = "";

    foreach (var item in file)
    {
        if (item != null)
        {
            tblImage img = new tblImage();
            img.ImageFile = new byte[item.ContentLength];
            img.ImageName = string.Format(@"{0}.JPG", Guid.NewGuid());
            img.vend_ID = Convert.ToInt32(Session["userID"]);

            item.InputStream.Read(img.ImageFile, 0, item.ContentLength);

            path = Path.Combine(Server.MapPath("~/Content/img"), img.ImageName);
            item.SaveAs(path);
            prodImages.Add(img);
        }
   }

   tblProduct.venodrID = Convert.ToInt32(Session["userID"]);
   tblProduct.tblImages = prodImages;

   if (ModelState.IsValid)
   {
       db.tblProducts.Add(tblProduct);
       db.SaveChanges();

       int latestProdID = tblProduct.productID;

       foreach (tblImage tblImg in tblProduct.tblImages)
       {
           tblImg.prod_ID = latestProdID;
           db.Entry(tblImg).State = EntityState.Modified;
       }

       db.SaveChanges();

       return RedirectToAction("DashBoard");
   }

   ViewBag.productCategory = new SelectList(db.tblCategories, "categoryID", "categoryName");
   ViewBag.vendorGender = new SelectList(db.tblGenders, "genderId", "genderName");

   return View();
}

I put a breakpoint on ModelState.IsValid and it is not going inside the if conditions and is returning back the same view without posting the data. Kindly tell me how to solve this issue

PS: I am new to ASP.NET MVC

[Bind(Include =

您可以在操作方法中绑定的check参数类似于您在“视图”中定义的参数,否则您可以删除bind属性并尝试这样做将帮助您找到实际的错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM