using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }
public string SomeFieldA { get; set; }
public string SomeFieldB { get; set; }
public class DbContext2 : DbContext
public DbContext2(DbContextOptions<DbContext2> options)
public DbSet<SomeDbObj> DbObjs { get; set; }
static void Main(string[] args)
var options = new DbContextOptionsBuilder<DbContext2>()
.UseInMemoryDatabase(databaseName: "Add_writes_to_database")
using (var context = new DbContext2(options))
var someOtherObj = new SomeDbObj { SomeFieldA = "A2" , SomeFieldB = "B2" };
var efTrackedThing = context.DbObjs.Add(new SomeDbObj { SomeFieldA = "A1" , SomeFieldB = "B1" });
someOtherObj.Id = efTrackedThing.Entity.Id;
context.DbObjs.Update(someOtherObj);
} catch (System.InvalidOperationException e) {
System.Console.WriteLine ("Attempt 1: Got exception on re-use: " + e.Message.Substring(50));
context.ChangeTracker.Clear();
context.DbObjs.Update(someOtherObj);
System.Console.WriteLine ("Attempt 2, after clearing change tracker. No Exception");