简体   繁体   English

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

[英]InnerException in Entity Framework when I try add an entity

I'm trying to insert a entity into my database with Entity Framework. 我正在尝试使用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. 我第一次运行我的应用程序,它工作,之后它停止工作,抛出此异常An error occurred while updating the entries. See the InnerException for details. An error occurred while updating the entries. See the InnerException for details. . (I'm really sure that I did not change anything). (我确信我没有改变任何事情)。

Why does the framework think I'm updating? 为什么框架认为我正在更新? And what am I wrong? 我错了什么?

SaveChanges will throw a System.Data.Entity.Infrastructure.DbUpdateException if your update command fails, and it wraps a System.Data.UpdateException that finally wraps a System.Data.SqlClient.SqlException . SaveChanges将抛出一个System.Data.Entity.Infrastructure.DbUpdateException当更新命令失败,它封装了System.Data.UpdateException终于包装了一个System.Data.SqlClient.SqlException It is also important to make a note that the inner-inner exception can be something other than a SqlException depending on the Entity Framework provider you are using. 同样重要的是要注意内部内部异常可能不是SqlException具体取决于您使用的Entity Framework提供程序。

If you unwrap these, you can get down to the raw SqlError objects that give you the specific details about problems with your update. 如果打开这些文件,可以查看原始SqlError对象, 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.DbEntityValidationException which will show you any validation errors that occurred during the call to SaveChanges . 您还可以通过捕获System.Data.Entity.Validation.DbEntityValidationException来获得大量功能和控制,它将显示在调用SaveChanges期间发生的任何验证错误。 The default behavior is to validate changes on save. 默认行为是验证保存时的更改。 You can also pre-validate changes by calling DbContext.GetValidationErrors() . 您还可以通过调用DbContext.GetValidationErrors()来预先验证更改。

It doesn't mean that you are doing an Update, that just means a SQL error occurred. 这并不意味着您正在进行更新,这只意味着发生了SQL错误。 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. 但同样,实际错误会给你更多细节。

If you are running in Visual Studio it should automatically break on the exception and you can expand the inner exception property. 如果您在Visual Studio中运行,它应该自动中断异常,您可以展开内部异常属性。 If not you can put a try/catch block and log it to a file or write to a console. 如果没有,您可以放置​​try / catch块并将其记录到文件或写入控制台。 Exception.ToString() will show all inner exceptions as well, as SQL errors tend to wrap the true error inside a few different exceptions. 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
    }
}

Based on Despertar's answer I could solved my problem. 根据Despertar的回答,我可以解决我的问题。 Entity Framework has an option called StoreGeneratedPattern . 实体框架有一个名为StoreGeneratedPattern的选项。 This option indicates the behavior when need to set an primary key id. 此选项指示需要设置主键ID时的行为。 By default this option is "None", so if you want the autoincrement, set the option StoreGeneratedPattern as "Identity" . 默认情况下,此选项为“None”,因此如果要进行自动增量,请将StoreGeneratedPattern选项StoreGeneratedPattern为“Identity”。 This is the link that I've read. 是我读过的链接。

Yes ... Always make sure that if our entities has guids then 'StoreGeneratedPattern' has to set with value "Identity". 是的...总是确保如果我们的实体有guid,那么'StoreGeneratedPattern'必须设置值“Identity”。 because by default sqlserver doesnot add values for guid columns. 因为默认情况下,sqlserver不会为guid列添加值。

It can be set from edmx by selecting entity-right click-properties-select guid column-set storedGeneratedPattern to identity. 它可以通过选择entity-right click-properties-select guid column-set storedGeneratedPattern to identity来从edmx设置。

Or by assigning 'Guid.newGuid()' value to column from code itself. 或者通过从代码本身向列分配'Guid.newGuid()'值。 ex. 恩。 product.Id = Guid.newGuid(); product.Id = Guid.newGuid();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试更新父实体时,实体框架正在更新子实体 - Entity Framework is updating child entity when I try to update parent entity 当我尝试获取值时实体框架挂起 - Entity Framework hangs when I try to get values 试试SaveChanges Entity FrameWork 5 - Try on SaveChanges Entity FrameWork 5 当我尝试映射实体(实体框架)的属性时,出现错误,类型“ __”必须是非空值类型 - When I try to map the properties for an entity (Entity Framework), I get the error the type '__' must be a non-nullable value type 实体框架添加新实体 - Entity framework add new entity 当我尝试通过Entity Framework中的路径/文件名打开MDF数据库时,为什么会出现此错误? - Why do I get this error when I try to open an MDF database via path/filename in Entity Framework? 实体框架 | 将实体添加到数据库中,其中包含其他实体 - Entity Framework | Add entity to DB with other entity in it 尝试添加到实体框架中的父实体时,我的子实体为空 - My child entity is null when trying to add to a parent in Entity Framework 添加实体时带有表名的实体框架错误 - Entity Framework bug with table name when add entity 错误 - 当我尝试在 .net core 2.2 中启用迁移时,项目上未安装实体框架包 - Error -The Entity Framework package is not installed on project when I try to enable migration in .net core 2.2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM