2

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

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();
}

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

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

4

4 回答 4

10

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

如果您打开这些,您可以深入了解原始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
    }
}

您还可以通过捕获System.Data.Entity.Validation.DbEntityValidationException显示在调用SaveChanges. 默认行为是在保存时验证更改。您还可以通过调用预先验证更改DbContext.GetValidationErrors()

于 2013-01-05T05:39:15.707 回答
4

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

如果您在 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
    }
}
于 2013-01-05T00:24:06.427 回答
0

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

于 2013-01-06T18:10:02.577 回答
0

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

它可以通过选择实体-右键单击-属性-选择guid列-设置storedGeneratedPattern来从edmx设置为身份。

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

于 2013-01-09T11:18:48.010 回答