无法将文件信息保存到数据库

Cannot save files info to db

我正在使用 ng-upload 和 ASP MVC,我的输入保存了多个文件。文件已成功保存在控制器中指定的文件夹路径中,但文件信息(id、名称、路径和 recipeId)未保存到 db。

控制器处理后 returns 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; }
}

Angular

$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:

我建议您在代码中添加一个 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;
            }

我删除了 async Taskawait db.SaveChangesAsync(); 所以我一直收到验证错误。问题是我在 File.cs 中将 StringLength 设置为 30 所以我增加了 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; }
}