![](/img/trans.png)
[英]ASP.Net MVC. How always include related data in Entity Framework queries?
[英]How to insert data into multiple tables in ASP. NET MVC. Entity Framework
我有兩個表tblProduct
和tblImages
。 tblImages
將為一個產品提供多個圖像,並具有與tblProduct
相關的外鍵。 將數據插入多個表時出現問題。
這是我的查看代碼:
<!-- 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>
這是我的控制器的代碼:
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();
}
我在ModelState.IsValid
上設置了一個斷點,它不在if條件內,並且在不發布數據的情況下返回了相同的視圖。 請告訴我如何解決這個問題
PS:我是ASP.NET MVC的新手
[Bind(Include =
您可以在操作方法中綁定的check參數類似於您在“視圖”中定義的參數,否則您可以刪除bind屬性並嘗試這樣做將幫助您找到實際的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.