在 entity framework 中使用图像和媒体文件的 CRUD 问题

Issue Working with CRUD for images and media files in entity framework

场景

我需要在我的数据库中将媒体文件存储为 VarBinary,将图像存储为 nvarchar 或 VarBinary(未定)。我正在使用 MVC5 和 entity framework。我已经为数据库中的另一个 table 创建了一个 CRUD 控制器,它不包含媒体文件或图像,并且工作正常。

到目前为止我做了什么

我创建了一个类别控制器,它与控制器一样基本,因为 table 的所有数据类型都是文本或数字。我已经为我的 MediaFiles 控制器和 Image 控制器复制了这个设计逻辑,但是我缺乏知识来调整它来处理转换这个文件和存储在数据库中的媒体文件。

型号

using System.Web;

namespace MediaOrganiser.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;


    public partial class Image
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Image()
        {
            MediaFiles = new HashSet<MediaFile>();
        }

        public long ImageID { get; set; }

        [Required]
        [StringLength(255)]
        public string Name { get; set; }

        [Required]
        public string FilePath { get; set; }

        public HttpPostedFileBase ImageFile { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<MediaFile> MediaFiles { get; set; }
    }
}

控制器

using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MediaOrganiser.Models;
using System.ComponentModel.DataAnnotations.Schema;

namespace MediaOrganiser.Controllers
{
    public class ImageController : Controller
    {
        IMediaRepository mediaRepository = null;
        public ImageController(IMediaRepository mediaRepository)
        {
            this.mediaRepository = mediaRepository;
        }
        public ImageController()
        : this(new SQLMediaRepository())
        {

        }
        // GET: Image
        public ActionResult Index()
        {

            return View();
        }

        // GET: Image/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Image/Create
        public ActionResult Create()
        {
            Image image = new Image();
            return View(image);
        }

        // POST: Image/Create
        [HttpPost]
        public ActionResult Create(Image im)
        {
            string fileName = Path.GetFileNameWithoutExtension(im.ImageFile.FileName);
            string extension = Path.GetExtension(im.ImageFile.FileName);
            fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
            im.FilePath = "~/Images/" + fileName;
            fileName = Path.Combine(Server.MapPath("~/Images/") + fileName);
            im.ImageFile.SaveAs(fileName);
            using (MediaEntities db = new MediaEntities())
            {
                db.Images.Add(im);
                db.SaveChanges();
            }
            ModelState.Clear();
            return View();
        }

        // GET: Image/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Image/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Image/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Image/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

创建视图

@model MediaOrganiser.Models.Image

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>


@using (Html.BeginForm("Create", "Image", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
                @Html.AntiForgeryToken()

                <div class="form-horizontal">
        <h4>Image</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FilePath, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">

                <input type="file" name="ImageFile" required />
                @Html.ValidationMessageFor(model => model.FilePath, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

我想要什么

当我尝试创建图像时,我收到以下错误消息:

Value cannot be null. Parameter name: entitySet

我希望能够在 C# 中创建 CRUD 方法以将以下内容存储在数据库中:

名称 - nvarchar(255)

文件路径 - nvarchar(最大)

我已经遵循了这个教程:https://www.youtube.com/watch?v=5L5W-AE-sEs

非常感谢任何帮助,谢谢。

您应该将 属性 public HttpPostedFileBase ImageFile { get; set; } 标记为 [NotMapped]

[NotMapped]
public HttpPostedFileBase ImageFile { get; set; }

与不应映射且不存在于数据库中的所有属性相同table。