Question

I overrode SaveChanges method to audit changes in EntityFramework. That works fine until I try to update associated object. When I try to update associated object, I get ArgumentException. I found out that exception is thrown after I read entities from ChangeTracker. If I do not do nothing with ChangeTracker in overriden SaveChanges method, object is succesfully updated. I use EntityFramework 5.0.

Don´t you know please if that is a bug or I´m doing something wrong?

Thrown exception:

System.ArgumentException was caught HResult=-2147024809
Message=The key-value pairs that define an EntityKey cannot be null or empty. Parameter name: record Source=System.Data.Entity
ParamName=record StackTrace: at System.Data.EntityKey.GetKeyValues(EntitySet entitySet, IExtendedDataRecord record, String[]& keyNames, Object& singletonKeyValue, Object[]& compositeKeyValues) at System.Data.EntityKey..ctor(EntitySet entitySet, IExtendedDataRecord record) at System.Data.Objects.ObjectStateManager.PerformDelete(IList1 entries) at System.Data.Objects.ObjectStateManager.DetectChanges() at System.Data.Objects.ObjectContext.DetectChanges() at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force) at System.Data.Entity.Internal.InternalContext.GetStateEntries(Func2 predicate) at System.Data.Entity.Internal.InternalContext.GetStateEntries() at System.Data.Entity.Infrastructure.DbChangeTracker.Entries() at System.Data.Entity.DbContext.GetValidationErrors() at System.Data.Entity.Internal.InternalContext.SaveChanges() at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at System.Data.Entity.DbContext.SaveChanges() at EFTest2.BlogContext.SaveChanges() in c:\Projects\EF22\EFTest2Solution\EFTest2\Context.cs:line 37 at EFTest2.Program.Main(String[] args) in c:\Projects\EF22\EFTest2Solution\EFTest2\Program.cs:line 42

My code looks this way: Program.cs

  class Program
  {
    static void Main(string[] args)
    {
      var configuration = new Configuration();
      configuration.TargetDatabase = new DbConnectionInfo("Data Source=server;Initial Catalog=EntityFramework;Integrated Security=True", "System.Data.SqlClient");
      var migrator = new DbMigrator(configuration);

      var scriptor = new MigratorScriptingDecorator(migrator);
      var script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);
      Console.WriteLine(script);

      var pending = migrator.GetPendingMigrations();

      migrator.Update();

      using (var ctx = new BlogContext())
      {
        Post post = new Post { Content = "Content", SpecialBlog = new Blog() { Title = "SpecialBlog" } };
        ctx.Posts.Add(post);
        ctx.SaveChanges();

        post.SpecialBlog = new Blog() { Title = "Update SpecialBlog" };

        ctx.SaveChanges(); // ArgumentException is thrown when using ChangeTracker
      }
    }
  }

Model

  public class Blog
  {
    public int? BlogId { get; set; }
    public string Title { get; set; }
    public ICollection<Post> Posts { get; set; }
  }

  public partial class BlogMap : EntityTypeConfiguration<Blog>
  {
    public BlogMap()
      : base()
    {
      HasKey(c => c.BlogId);
      Property(c => c.Title).IsRequired().HasMaxLength(40);
      ToTable("Blog");
    }
  }

  public class Post 
  {
    public int? PostId { get; set; }
    public string Content { get; set; }

    public int? BlogId { get; set; }
    public Blog Blog { get; set; }
    public int? SpecialBlogId { get; set; }
    public Blog SpecialBlog { get; set; }
  }

  public partial class PostMap : EntityTypeConfiguration<Post>
  {
    public PostMap()
      : base()
    {
      HasKey(c => c.PostId);

      Property(c => c.Content);

      HasOptional(m => m.Blog)
                    .WithMany(t => t.Posts)
                    .HasForeignKey(m => m.BlogId)
                    .WillCascadeOnDelete(false);

      HasOptional(m => m.SpecialBlog)
                    .WithMany()
                    .HasForeignKey(m => m.SpecialBlogId)
                    .WillCascadeOnDelete(false);

      ToTable("Post");
    }
  }

Context:

  public class BlogContext : DbContext
  {
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      Database.SetInitializer(new DropCreateDatabaseAlways<BlogContext>());

      modelBuilder.Configurations.Add(new PostMap());
      modelBuilder.Configurations.Add(new BlogMap());
    }

    public override int SaveChanges()
    {
      var entries = ChangeTracker.Entries(); // causes ArgumentNullException after calling base.SaveChanges();

      return base.SaveChanges();
    }
  }

Configuration

  public class Configuration : DbMigrationsConfiguration<BlogContext>
  {
    public Configuration()
    {
      AutomaticMigrationsEnabled = true;
      AutomaticMigrationDataLossAllowed = true;
    }
  }
Was it helpful?

Solution

Reaction from msdn... it is a bug. To fix it is necessary to use non-nullable primary keys.

Bug is reported at EF codeplex site: Exception thrown when calling detect changes twice with nullable primary keys

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top