我正在使用ng-upload和ASP MVC,我的输入会保存多个文件。文件成功保存在控制器中指定的文件夹路径中,但文件信息(id,name,path和recipeId)未保存到db。
在控制器处理之后,它将null
返回到视图。
File.cs
public class File
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name = "Name")]
[StringLength(30, ErrorMessage = "Name cannot be longer than 30 characters.")]
public string Name { get; set; }
[Display(Name = "Path")]
[StringLength(100, ErrorMessage = "Path cannot be longer than 30 characters.")]
public string Path { get; set; }
[ForeignKey("Recipe")]
public int RecipeId { get; set; }
public virtual Recipe Recipe { get; set; }
}
角
$scope.SelectedFiles = files;
if ($scope.SelectedFiles && $scope.SelectedFiles.length) {
Upload.upload({
url: '/Files/Upload/',
data: {
files: $scope.SelectedFiles,
RecipeId: $scope.recipeID
}
}).then(function (response) {
$timeout(function () {
$scope.Result = response.data;
});
}, function (response) {
if (response.status > 0) {
var errorMsg = response.status + ': ' + response.data;
alert(errorMsg);
} else {
console.log(response.data);
}
}, function (evt) {
$scope.Progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
控制器
[HttpPost]
public ContentResult Upload(File vm)
{
string path = Server.MapPath("~/Uploads/");
int RecipeId = vm.RecipeId;
foreach (string key in Request.Files)
{
HttpPostedFileBase postedFile = Request.Files[key];
postedFile.SaveAs(path + postedFile.FileName);
File recipefile = new File();
recipefile.Name = postedFile.FileName;
recipefile.Path = path;
recipefile.RecipeId = RecipeId;
db.Files.Add(recipefile);
}
db.SaveChanges();
return Content("Success");
}
我收到以下错误。
System.Data.Entity.Validation.DbEntityValidationException was unhandled by user code
HResult=-2146232032
Message=Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Source=FAC Recipes
StackTrace:
at FACRecipes.Controllers.FilesController.Upload(File vm) in ...Controllers\FilesController.cs:line 52
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
InnerException:
答案 0 :(得分:0)
我建议你在代码中添加一个try catch块然后 使你的catch块像这样它将帮助你找到实际的错误
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw dbEx;
}
答案 1 :(得分:0)
我删除了async Task
和await db.SaveChangesAsync();
,因此我不断收到验证错误。问题是我在StringLength
中将30
设置为File.cs
所以我增加了StringLength
并且它有效!谢谢大家!
public class File
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name = "Name")]
[StringLength(500)
public string Name { get; set; }
[Display(Name = "Path")]
[StringLength(100)]
public string Path { get; set; }
[ForeignKey("Recipe")]
public int RecipeId { get; set; }
public virtual Recipe Recipe { get; set; }
}