I'm using ASP.NET MVC and Entity Framework code-first approach. I want to upload a file (.doc
or .pdf
) to a SQL Server. I have searched and browsed through many forums but couldn't find a definite solution for uploading a file to SQL Server using Entity Framework code-first approach.
I have written the following code to upload a file but am getting an error while saving the file to database.
Here is the following code
The controller is :
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();
}
}
}
The class filedump
for creating database is :
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; }
}
}
The entities class is :
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; }
}
}
The connection string:
<connectionStrings>
<add name="FinalEntities"
connectionString="Data Source=|DataDirectory|FinaleuploadEF.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
I am getting the following error while saving a file to the database:
www.freeimagehosting.net/kmwts
Can anyone please suggest a solution for the above problem? Or any changes required in the above code?
EntityValidationErros
property, so you can get more clear picture of actual error. – Furqan Jun 23 at 11:15