question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

InvalidOperationException saving entity

See original GitHub issue

I am currently using Beta 8

User model

public class User 
{
     public string Id { get; set; }
     public string Email { get; set; }
}

Saving the entity

    _db.Users.Add(user);
    await _db.SaveChangesAsync();

When i try to save the entity i get the following exception, and i am not sure why and what this means. The entity is created in the DB, so it seems to be working, but EF throws this exception. Not sure if this is a bug, or just me doing something wrong.

An unhandled exception occurred while processing the request. InvalidOperationException: The >property ‘Id’ on entity type ‘User’ has a temporary value while attempting to change the entity’s >state to ‘Unchanged’. Either set a permanent value explicitly or ensure that the database is >configured to generate values for this property.

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:9 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
rowanmillercommented, Nov 6, 2015

Hey,

Sounds like you are probably trying to save a User without assigning a primary key value. In the following code the first SaveChanges succeeds, but the second one throws the exception you are seeing.

using Microsoft.Data.Entity;

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db  = new UserContext())
            {
                db.Database.EnsureCreated();

                db.Users.Add(new User { Id = "user1", Email = "user1@sample.com" });
                db.SaveChanges();

                db.Users.Add(new User { Email = "user2@sample.com" });
                db.SaveChanges();
            }
        }
    }

    public class User
    {
        public string Id { get; set; }
        public string Email { get; set; }
    }

    public class UserContext : DbContext
    {
        public DbSet<User> Users { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Demo;Trusted_Connection=True;");
        }
    }
}

In RC1 we have made some changes in this area to try and make things a little clearer. Instead of that exception during SaveChanges you now get this when you try to add the entity.

System.InvalidOperationException: The instance of entity type ‘ConsoleApplication10.User’ cannot be tracked because it has an invalid (e.g. null or CLR default) primary key. Either set the key explicitly or consider using an IValueGenerator to generate unique key values.

0reactions
ajcvickerscommented, Dec 22, 2017

@ppumkin DbContext is not thread-safe. That is, the same instance cannot be used by multiple threads concurrently. Tasks.WaitAll is causing that to happen, so it can’t be used for this kind of thing.

Read more comments on GitHub >

github_iconTop Results From Across the Web

InvalidOperationException when calling SaveChanges in . ...
Solution: Augmenting function SaveChanges(System.Data.Objects.SaveOptions.None) prevents system to use temporary EntityKeys in state of object ...
Read more >
InvalidOperationException: Cannot save changes for an ...
An exception occurred in the database while saving changes for context type 'Buttons.Data.ButtonContext'. System.InvalidOperationException: ...
Read more >
InvalidOperationException Class (System)
An InvalidOperationException is thrown when you try to access a UI element from a thread other than the UI thread. The text of...
Read more >
Breaking changes in EF Core 6.0
InvalidOperationException : Entity type 'ContactInfo' is an optional dependent ... This prevents data loss when querying and saving data.
Read more >
Hands-On Domain-Driven Design with .NET Core: Tackling ...
Save (classifiedAd); break; case V1. ... Id.ToString()); if (classifiedAd == null) throw new InvalidOperationException( $"Entity with id {cmd.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found