C# SaveChanges() 上的验证错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19520022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:10:58  来源:igfitidea点击:

Validation Error on SaveChanges()

c#asp.netasp.net-mvcentity-framework

提问by john Gu

I have the following Action method inside my Asp.net mvc web application:-

我的 Asp.net mvc Web 应用程序中有以下 Action 方法:-

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(SDJoin sdj, FormCollection formValues)
{
    Try
    {
        //code goes here
        repository.InsertOrUpdateSD(sdj.StorageDevice, User.Identity.Name, assetid);
        repository.Save();
    }
    catch (Exception ex)
    {
        //code goes here
    }
    PopulateViewBagData();
    return View(sdj);
}

which calls the following method:-

它调用以下方法:-

public void InsertOrUpdateSD(TMSStorageDevice sd, string username, long assetid)
{
    var resource = entities.Resources.AsNoTracking().SingleOrDefault(a => a.RESOURCEID == assetid);
    if (sd.TMSStorageDeviceID == default(int))
    {
        // New entity
        int technologyypeID = GetTechnologyTypeID("Storage Device");
        Technology technology = new Technology
        {
            IsDeleted = true,
            IsCompleted = false,
            TypeID = technologyypeID,
            Tag = "SD" + GetTagMaximumeNumber2(technologyypeID).ToString(),
            StartDate = DateTime.Now,
            IT360ID = assetid
        };

        InsertOrUpdateTechnology(technology);
        Save();

        sd.TMSStorageDeviceID = technology.TechnologyID;
        tms.TMSStorageDevices.Add(sd);
    }
}

My model class is as follow:-

我的模型类如下:-

public partial class TMSStorageDevice
{
    public int TMSStorageDeviceID { get; set; }
    public string Name { get; set; }
    public Nullable<decimal> size { get; set; }
    public int RackID { get; set; }
    public string CustomerName { get; set; }
    public string Comment { get; set; }
    public byte[] timestamp { get; set; }

    public virtual Technology Technology { get; set; }
    public virtual TMSRack TMSRack { get; set; }
}

but if i call the Create action method i will get the following exception:-

但是如果我调用 Create action 方法,我会得到以下异常:-

System.Data.Entity.Validation.DbEntityValidationException was caught
  HResult=-2146232032
  Message=Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.Internal.InternalContext.SaveChanges()
       at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
       at System.Data.Entity.DbContext.SaveChanges()
       at TMS.Models.Repository.Save() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\TMS\TMS\Models\Repository.cs:line 1926
       at TMS.Controllers.StorageDeviceController.Create(SDJoin sdj, FormCollection formValues) in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\TMS\TMS\Controllers\StorageDeviceController.cs:line 160
  InnerException:

Can anyone advice what is wrong, as i double check my code and every thing should work fine ? Thanks

任何人都可以建议出了什么问题,因为我仔细检查了我的代码并且每件事都应该正常工作?谢谢

采纳答案by qujck

You haven't shown the Save()method but if you can add code like this to it you'll get an exception that contains all the details you're looking for

您尚未显示该Save()方法,但如果您可以向其中添加这样的代码,您将收到一个异常,其中包含您要查找的所有详细信息

try
{
    _context.SaveChanges();
}
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 raise;
}

回答by Roman Lemko

I know the question is old now, but I hope someone finds this useful, too.

我知道这个问题现在已经过时了,但我希望有人也觉得这很有用。

  1. Most likely (and indeed, judging by your comments) the error was that your variable doesn't pass Model validation.
  2. The other way to see the errors you couldn't see (without changing the code) is to look at the exception using the QuickWatch window. The problem is that 'View Details' window that you can open from exception tooltip doesn't show EntityValidationErrors. And without a catch block you don't have any exception variable you can look at in QuickWatch. Luckily, QuickWatch has PseudoVariables. So, using "$exception" pseudovariable you can easily take a look at the current unhandled exception in QuickWatch window.(Please, see screenshots below) Exception Details windowand QuickWatch window with $exception pseudovariable
  1. 最有可能(实际上,根据您的评论判断)错误是您的变量未通过模型验证。
  2. 查看您看不到的错误(不更改代码)的另一种方法是使用 QuickWatch 窗口查看异常。问题是您可以从异常工具提示打开的“查看详细信息”窗口不显示 EntityValidationErrors。如果没有 catch 块,您就没有任何可以在 QuickWatch 中查看的异常变量。幸运的是,QuickWatch 有 PseudoVariables。 因此,使用 "$exception" 伪变量,您可以轻松查看 QuickWatch 窗口中当前未处理的异常。(请参阅下面的屏幕截图) 带有 $exception 伪变量的异常详细信息窗口QuickWatch 窗口

回答by singhswat

Although this is an old post but this approach can be more fruitful!

虽然这是一个旧帖子,但这种方法可以更有成效!

Credits

学分

Try something like this

尝试这样的事情

        try
        {
            pcontext.SaveChanges();
        }
       catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException ex)
        {             
             Console.WriteLine(ex.InnerException);
        }
        catch (System.Data.Entity.Core.EntityCommandCompilationException ex)
        {
          Console.WriteLine(ex.InnerException);
        }
        catch (System.Data.Entity.Core.UpdateException ex)
        {
         Console.WriteLine(ex.InnerException);
        }

        catch (System.Data.Entity.Infrastructure.DbUpdateException ex) //DbContext
        {
            Console.WriteLine(ex.InnerException);
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex.InnerException);
            throw;
        }