【问题标题】:How To Save data in Two Table in mvc4如何在 mvc4 中将数据保存在两个表中
【发布时间】:2016-02-18 10:40:24
【问题描述】:

我有两张桌子

1- P_产品

2- P_Imagepath

我想根据第一个表的 Id 将输入数据存储在 P_Product 表中。我想使用 P_Product Id 将图像存储到 P_Imagepath 表中。

这里我试过了,但它显示了一些错误

在 Foreach 循环中,它显示“新表达式需要 (),[],{}after type”,并且在“item”中,它的节目不能隐式转换类型 System.web.HttpPostedFileBase 到字符串

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(P_Product p_product,List<HttpPostedFileBase> Base)
        {      
            if (ModelState.IsValid)
            {
                db.P_Product.Add(p_product);                
                db.SaveChanges();
                P_Product product = db.P_Product.LastOrDefault();
                int p = product.Id;
                List<P_ImagePath>images=new List<P_ImagePath>
                foreach(var item in Base)
                {
                    P_ImagePath image=new P_ImagePath();
                    image.P_Id=p;
                    image.ImagePath=item;
                    images.Add(image);
                }
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.Cat_Id = new SelectList(db.P_Category, "Id", "Name", p_product.Cat_Id);           
            return View(p_product);
        }

【问题讨论】:

  • 你遇到了什么错误?
  • 在 Foreach 循环中显示“一个新的表达式需要 (),[],{}after type”,并且在“item”中它的显示不能将 System.web.HttpPostedFileBase 类型隐式转换为字符串跨度>
  • 将其添加到您的问题中。
  • 尝试 base[item] 而不是 item
  • base[item] 不工作

标签: asp.net sql-server asp.net-mvc-4


【解决方案1】:
//this line has syntax error - missing "();"
//correct form: List<P_ImagePath>images=new List<P_ImagePath>();
List<P_ImagePath>images=new List<P_ImagePath> 

您的 image.ImagePath 可能是字符串(它是),而 item 是 Base 列表中的项目,这意味着该项目的类型是 HttpPostedFileBase em>(方法参数),所以你不能把它转换成字符串。

您可以做的是从item 中找到该文件的路径。所以,试试这个:

...
foreach(var item in Base)
{
    P_ImagePath image=new P_ImagePath();
    image.P_Id=p;
    image.ImagePath= Path.GetFileName(item.FileName);
    images.Add(image);
}

【讨论】:

  • 在我的代码中使用此更改后,它无法正常工作,其显示错误如LINQ to Entities does not recognize the method 'UploadRecords.Models.P_Product LastOrDefault[P_Product](System.Linq.IQueryable1[UploadRecords.Models.P_Product])' 方法,并且此方法无法转换为商店表达式。`跨度>
猜你喜欢
  • 1970-01-01
  • 2014-10-27
  • 1970-01-01
  • 2013-01-21
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
相关资源
最近更新 更多