C# 尝试添加实体时实体框架中的 InnerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14167045/
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 10:56:34  来源:igfitidea点击:

InnerException in Entity Framework when I try add an entity

c#visual-studio-2010entity-frameworkentity-relationship

提问by Cristhian Boujon

I'm trying to insert a entity into my database with Entity Framework. See below:

我正在尝试使用实体框架将实体插入到我的数据库中。见下文:

private void InsertarIntoDataBase()
{

    Juego game = db.games.First(g => g.Id == anId);
    Day d = new Day {
                       DayNumber = this.Number,
                       Game = game // This is a relationship. One Day has one game 
                    };
    db.AddToDay(d);
    db.SaveChanges();
}

This is always for an insert, not an update. The first time that I run my app, it works, afterwards it stops working, throwing this exception An error occurred while updating the entries. See the InnerException for details.. (I'm really sure that I did not change anything).

这始终用于插入,而不是更新。我第一次运行我的应用程序时,它可以工作,然后它停止工作,抛出这个异常An error occurred while updating the entries. See the InnerException for details.。(我真的很确定我没有改变任何东西)。

Why does the framework think I'm updating? And what am I wrong?

为什么框架认为我正在更新?我错了什么?

采纳答案by Despertar

It doesn't mean that you are doing an Update, that just means a SQL error occurred. You need to read the inner exception to find out what the actual error is. From the looks of it, it may be something related to a primary key, or foreign key constraint, ie. you are adding an item and that primary key is already in the table. But again, the actual error will give you more details.

这并不意味着您正在执行更新,这仅意味着发生了 SQL 错误。您需要阅读内部异常以找出实际错误是什么。从它的外观来看,它可能与主键或外键约束相关,即。您正在添加一个项目并且该主键已经在表中。但同样,实际错误将为您提供更多详细信息。

If you are running in Visual Studio it should automatically break on the exception and you can expand the inner exception property. If not you can put a try/catch block and log it to a file or write to a console. Exception.ToString() will show all inner exceptions as well, as SQL errors tend to wrap the true error inside a few different exceptions.

如果您在 Visual Studio 中运行,它应该会自动中断异常,您可以展开内部异常属性。如果没有,您可以放置​​一个 try/catch 块并将其记录到文件或写入控制台。Exception.ToString() 也将显示所有内部异常,因为 SQL 错误倾向于将真正的错误包装在几个不同的异常中。

private void InsertarIntoDataBase()
{
    try 
    {
        Juego game = db.games.First(g => g.Id == anId);
        Day d = new Day {
                           DayNumber = this.Number,
                           Game = game // This is a relationship. One Day has one game 
                        };
        db.AddToDay(d);
        db.SaveChanges();
    }
    catch (Exception e)
    {
        Console.WriteLine(e); // or log to file, etc.
        throw; // re-throw the exception if you want it to continue up the stack
    }
}

回答by David Anderson

SaveChangeswill throw a System.Data.Entity.Infrastructure.DbUpdateExceptionif your update command fails, and it wraps a System.Data.UpdateExceptionthat finally wraps a System.Data.SqlClient.SqlException. It is also important to make a note that the inner-inner exception can be something other than a SqlExceptiondepending on the Entity Framework provider you are using.

SaveChangesSystem.Data.Entity.Infrastructure.DbUpdateException如果您的更新命令失败,将抛出 a ,并且它包装 a System.Data.UpdateException,最终包装 a System.Data.SqlClient.SqlException。同样重要的是要注意内部异常可能不是 aSqlException取决于您使用的实体框架提供程序。

If you unwrap these, you can get down to the raw SqlErrorobjects that give you the specific details about problems with your update.

如果您打开这些文件,您可以深入了解原始SqlError对象,这些对象为您提供有关更新问题的具体详细信息。

try 
{
    db.SaveChanges();
}
catch (DbUpdateException ex) 
{
    UpdateException updateException = (UpdateException)ex.InnerException;
    SqlException sqlException = (SqlException)updateException.InnerException;

    foreach (SqlError error in sqlException.Errors)
    {
        // TODO: Do something with your errors
    }
}

You can also gain a lot of power and control by also catching System.Data.Entity.Validation.DbEntityValidationExceptionwhich will show you any validation errors that occurred during the call to SaveChanges. The default behavior is to validate changes on save. You can also pre-validate changes by calling DbContext.GetValidationErrors().

您还可以通过捕获System.Data.Entity.Validation.DbEntityValidationException来获得大量的权力和控制,这将向您显示在调用SaveChanges. 默认行为是在保存时验证更改。您还可以通过调用预验证更改DbContext.GetValidationErrors()

回答by Cristhian Boujon

Based on Despertar's answer I could solved my problem. Entity Framework has an option called StoreGeneratedPattern. This option indicates the behavior when need to set an primary key id. By default this option is "None", so if you want the autoincrement, set the option StoreGeneratedPatternas "Identity" . Thisis the link that I've read.

根据 Despertar 的回答,我可以解决我的问题。实体框架有一个名为StoreGeneratedPattern. 此选项指示需要设置主键 id 时的行为。默认情况下,此选项为 "None",因此如果您想要自动增量,请将选项设置StoreGeneratedPattern为 "Identity" 。是我读过的链接。

回答by sachin

Yes ... Always make sure that if our entities has guids then 'StoreGeneratedPattern' has to set with value "Identity". because by default sqlserver doesnot add values for guid columns.

是的...始终确保如果我们的实体具有 guid,则 'StoreGeneratedPattern' 必须设置为值“Identity”。因为默认情况下 sqlserver 不会为 guid 列添加值。

It can be set from edmx by selecting entity-right click-properties-select guid column-set storedGeneratedPattern to identity.

它可以通过选择实体-右键单击-属性-选择 guid 列-将存储的生成模式设置为身份来从 edmx 中设置。

Or by assigning 'Guid.newGuid()' value to column from code itself. ex. product.Id = Guid.newGuid();

或者通过将 'Guid.newGuid()' 值分配给代码本身的列。前任。product.Id = Guid.newGuid();