无法将图像存储到数据库

时间:2015-10-12 21:13:38

标签: asp.net asp.net-mvc entity-framework-4

以下代码:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Car model, HttpPostedFileBase file)
    {
        var currentUser = UserManager.FindById(User.Identity.GetUserId());
        var user = this.db.Users.Where(u => u.Id == currentUser.Id).FirstOrDefault();

        if(ModelState.IsValid)
        {

            if (file != null && file.ContentLength > 0)
            {
                var photo = new FilePath
                {
                    FileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName),
                    FileType = FileType.Photo
                };
                model.FilePaths = new List<FilePath>();
                model.FilePaths.Add(photo);
                file.SaveAs(Path.Combine(Server.MapPath("~/Images/"), photo.FileName));

            }
            user.Cars.Add(model);
            db.SaveChanges();

            return RedirectToAction("Default", "Home");
        }

        SetCategoryViewBag(model.Category.CategoryId);

        return View(model);
       }

不允许我将任何图像存储到数据库中。图像表根本不存储任何信息。但是,汽车表是可以的,但图像仍然显示为空。

我在这里做错了什么?

编辑:

车型:

    public class Car
{
    [Key]
    public int CarId { get; set; }
    public string Title { get; set; }
    public int Price { get; set; }
    public virtual Category Category { get; set; }
    public int CategoryId { get; set; }
    public virtual ICollection<FilePath> FilePaths { get; set; }

}

FilePath模型:

  public class FilePath
{
    public int FilePathId { get; set; }
    [StringLength(255)]
    public string FileName { get; set; }
    public FileType FileType { get; set; }

    public int CarId { get; set; }

   public virtual Car Cars { get; set; }

}

0 个答案:

没有答案