Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

c# - InvalidOperationException when calling SaveChanges in .NET Entity framework

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.

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.

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)

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...