上载文件时出错:System.InvalidOperationException:'实体类型Document不是当前上下文模型的一部分. [英] Error when uploading file: System.InvalidOperationException: 'The entity type Document is not part of the model for the current context.'
本文介绍了上载文件时出错:System.InvalidOperationException:'实体类型Document不是当前上下文模型的一部分.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试将文件上传到文件夹时出现以下错误:
I am getting below error when trying to upload a file to a folder:
System.InvalidOperationException:'实体类型Document不是当前上下文模型的一部分."
System.InvalidOperationException: 'The entity type Document is not part of the model for the current context.'
这是代码:
public ActionResult AddHRDocument()
{
DocumentsConn db = new DocumentsConn();
return View();
}
[HttpPost]
public ActionResult AddHRDocument(HttpPostedFileBase file)
{
//Extract Image File Name.
string fileName = System.IO.Path.GetFileName(file.FileName);
//Set the Image File Path.
string filePath = "~/Documents/HR/" + fileName;
//Save the Image File in Folder.
file.SaveAs(Server.MapPath(filePath));
//Insert the Image File details in Table.
DocumentsConn db = new DocumentsConn();
db.Documents.Add(new Document
{
DocumentName = fileName,
Document_url = filePath
});
db.SaveChanges();
}
推荐答案
我使用此代码上传了多个文件.您可以编辑0ne文件的代码.
I used this code for upload multi files.you can edit your code for 0ne file.
查看:编写 enctype ="multipart/form-data"
@using (Html.BeginForm("ActionName", "ControolerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
上传文件框:
@Html.TextBoxFor(Model => Model.Files, new { type = "file", name = "Files", multiple = "multiple", @class = "form-control", accept = "image/*" })
在操作中使用以下代码从请求中获取文件:
use below code in your action for get files from request:
[HttpPost]
public ActionResult UploadFile(long Id)
不需要动作输入参数 HttpPostedFileBase .
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
string fileName = Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName)?.ToLower();
string path = Server.MapPath("~") + "Files\\UploadImages\\" + fileName;
//TODO: Fill Properties Table.example: DocType Or Id Or AddressFile
// entity.DocType = System.IO.Path.GetExtension(file.FileName)?.ToLower();
if (File.DocType?.ToLower() == ".png" || File.DocType?.ToLower() == ".img"
|| File.DocType?.ToLower() == ".jpeg"
|| File.DocType?.ToLower() == ".jpg")
{
file.SaveAs(path);
//TODO: Save Info File In Database
}
这篇关于上载文件时出错:System.InvalidOperationException:'实体类型Document不是当前上下文模型的一部分.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文