C# 在 .NET 实体框架中调用 SaveChanges 时出现 InvalidOperationException

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

InvalidOperationException when calling SaveChanges in .NET Entity framework

c#.netentity-framework

提问by Paxxi

I'm trying to learn how to use the Entity framework but I've hit an issue I can't solve. What I'm doing is that I'm walking through a list of Movies that I have and inserts each one into a simple database.

我正在尝试学习如何使用实体框架,但遇到了一个无法解决的问题。我正在做的是浏览我拥有的电影列表并将每个电影插入到一个简单的数据库中。

This is the code I'm using

这是我正在使用的代码

private void AddMovies(DirectoryInfo dir)
{
    MovieEntities db = new MovieEntities();
    foreach (DirectoryInfo d in dir.GetDirectories())
    {
        Movie m = new Movie { Name = d.Name, Path = dir.FullName };
        db.AddToMovies(movie);
    }
    db.SaveChanges();
}

When I do this I get an exception at db.SaveChanges() that read.

当我这样做时,我在 db.SaveChanges() 读取异常。

The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.

对数据库的更改已成功提交,但在更新对象上下文时发生错误。ObjectContext 可能处于不一致的状态。内部异常消息:AcceptChanges 无法继续,因为对象的键值与 ObjectStateManager 中的另一个对象冲突。在调用 AcceptChanges 之前确保键值是唯一的。

I haven't been able to find out what's causing this issue. My database table contains three columns
Id int autoincrement
Name nchar(255)
Path nchar(255)

我一直无法找出导致此问题的原因。我的数据库表包含三列
Id int autoincrement
Name nchar(255)
Path nchar(255)

Update: I Checked my edmx file and the SSDL section have the StoreGeneratedPattern="Identity" as suggested. I also followed the blog post and tried to add ClientAutoGenerated="true" and StoreGenerated="true" in the CSDL as suggested there. This resulted in compile errors ( Error 5: The 'ClientAutoGenerated' attribute is not allowed.). Since the blog post is from 2006 and it has a link to a follow up post I assume it's been changed.

更新:我检查了我的 edmx 文件和 SSDL 部分有建议的 StoreGeneratedPattern="Identity"。我还关注了博客文章,并尝试按照那里的建议在 CSDL 中添加 ClientAutoGenerated="true" 和 StoreGenerated="true"。这导致了编译错误(错误 5:不允许使用“ClientAutoGenerated”属性。)。由于博客文章是 2006 年的,并且它有一个后续文章的链接,我认为它已被更改。

However, I cannot read the followup post since it seems to require an msdn account.

但是,我无法阅读后续帖子,因为它似乎需要一个 msdn 帐户。

采纳答案by Paxxi

I found the solution to this.

我找到了解决方案。

What happened was that when I created my table I forgot to add the primary key and set (Is Identity) property to yes. I then created my Entity model and got this error.

发生的事情是,当我创建我的表时,我忘记添加主键并将 (Is Identity) 属性设置为是。然后我创建了我的实体模型并收到此错误。

I went back and fixed my database table but I still hade the weird Exception. What solved the problem in the end was to remove the entity and re-create it after the table was fixed.

我回去修复了我的数据库表,但我仍然遇到了奇怪的异常。最终解决问题的是将实体移除并在表修复后重新创建它。

No more exceptions :)

没有更多的例外:)

回答by Max Galkin

This exception seems to tell you that you have equal values in severals rows in the Id column, which is supposed to only have unique values, because it's a key column. Entity Framework can handle such columns in two ways: either you (the Client) generates unique values, or the Server generates unique values. In your case it seems logical to allow the Server to generate autoincremented keys.

这个异常似乎告诉你,你在 Id 列的几行中有相等的值,它应该只有唯一的值,因为它是一个关键列。实体框架可以通过两种方式处理此类列:您(客户端)生成唯一值,或者服务器生成唯一值。在您的情况下,允许服务器生成自动递增的密钥似乎是合乎逻辑的。

Do you have the StoreGeneratedPatternkey set for the Id column in your SSDL file?

您是否StoreGeneratedPattern为 SSDL 文件中的 Id 列设置了密钥?

Here is an example from this blogpost:

这是这篇博文中的一个例子:

<EntityType Name="rooms" Key="id">
    <Property Name="id" Type="int" Nullable="false" 
              StoreGeneratedPattern="Identity" />
    <Property Name="name" Type="nvarchar" Nullable="false" MaxLength="50" />
</EntityType>

回答by Paxxi

if you have a bindingsource bound, you should call the suspendbinding:

如果你有一个 bindingsource 绑定,你应该调用 suspendbinding:

        bs.SuspendBinding();
        Data.SaveChanges();
        bs.ResumeBinding();

回答by Mohamed A. Alrshah

last time I tried the following code and I said it is working fine

上次我尝试了以下代码,我说它工作正常

bs.SuspendBinding();
Data.SaveChanges();
bs.ResumeBinding();

The important things which I wana tell you today are that:

我今天想告诉你的重要事情是:

1- if we use the above code to suspend binding we have to do more code to fix a lot of scenarios like index lost in the collections and the master detail bindings

1-如果我们使用上面的代码来暂停绑定,我们必须做更多的代码来修复很多情况,比如集合中的索引丢失和主细节绑定

2- if we use the following code instead of the above code we will see the exception gone and every thing will be ok where no need to write more code

2-如果我们使用以下代码而不是上面的代码,我们将看到异常消失,一切都会好起来的,无需编写更多代码

        Data.SaveChanges(System.Data.Objects.SaveOptions.None);

I hope this solves your similar problems

我希望这可以解决您的类似问题

thank you friends

谢谢朋友

回答by Morad

System.Data.Objects.SaveOptions.None

This solves the problem but I'm wondering what's the difference between uning none or the other options.

这解决了问题,但我想知道 uning none 或其他选项之间有什么区别。

回答by Mahika

Check if Primary Keys are missing in any of your etities, if yes, then create them, and do the "UpdateModel from Database"

检查您的任何实体中是否缺少主键,如果是,则创建它们,并执行“从数据库更新模型”

this should Solve the problem

这应该可以解决问题

回答by major

Also Check if you set the "Is Identity" property for another column to "yes" and you are inserting a duplicated values into it.

还要检查您是否将另一列的“Is Identity”属性设置为“yes”,并且您是否在其中插入了重复的值。

回答by A_Basit

I had the similar issue with table relationship spanning three levels Like Customer->Order->Order-Details with oracle 12C Auto-ID Trigger for key generation. Insertion using SaveChanges()was throwing System.InvalidOperationException.

我遇到了跨越三个级别的表关系的类似问题,例如 Customer->Order->Order-Details 与 oracle 12C Auto-ID Trigger for key generation。插入使用SaveChanges()被抛出System.InvalidOperationException

Solution: Augmenting function SaveChanges(System.Data.Objects.SaveOptions.None)prevents system to use temporary EntityKeysin state of object graph and in result exception is avoided.

解决方案:Augment 函数SaveChanges(System.Data.Objects.SaveOptions.None)防止系统EntityKeys在对象图的状态中使用临时的,并避免结果异常。