我正在使用 ASP.NET MVC 和实体框架代码优先方法。我想将文件(.doc
或.pdf
)上传到 SQL Server。我搜索并浏览了许多论坛,但找不到使用实体框架代码优先方法将文件上传到 SQL Server 的明确解决方案。
我编写了以下代码来上传文件,但在将文件保存到数据库时出现错误。
这是以下代码
控制器是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using FileuploadEF.Models;
namespace FileuploadEF.Controllers
{
public class HomeController : Controller
{
FileEntities db = new FileEntities();
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult upload()
{
foreach (string file in Request.Files)
{
var PostedFile = Request.Files[file];
string filetype = Request.Files[file].ContentType;
int filelength = Request.Files[file].ContentLength;
Stream filestream = Request.Files[file].InputStream;
byte[] filedata = new byte[filelength];
string filename= Path.GetFileName(Request.Files[file].FileName);
filestream.Read(filedata, 0, filelength);
var data = new FileDump
{
FileName = filename,
FileType = filetype,
FileContent = filedata
};
db.FileDumps.Add(data);
db.SaveChanges();
}
return View();
}
}
}
创建数据库的类filedump
是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FinaleuploadEF.Models
{
public class FileDump
{
public int Id { get; set; }
public string FileName { get; set; }
public string FileType { get; set; }
public byte[] FileContent { get; set; }
}
}
实体类是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace FinaleuploadEF.Models
{
public class FinalEntities : DbContext
{
public DbSet<FileDump> FileDumps { get; set; }
}
}
连接字符串:
<connectionStrings>
<add name="FinalEntities"
connectionString="Data Source=|DataDirectory|FinaleuploadEF.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
将文件保存到数据库时出现以下错误:
www.freeimagehosting.net/kmwts
任何人都可以为上述问题提出解决方案吗?或者上述代码中需要进行任何更改?