{"action":"created","issue":{"url":"https://api.github.com/repos/aspnet/EntityFramework/issues/4488","repository_url":"https://api.github.com/repos/aspnet/EntityFramework","labels_url":"https://api.github.com/repos/aspnet/EntityFramework/issues/4488/labels{/name}","comments_url":"https://api.github.com/repos/aspnet/EntityFramework/issues/4488/comments","events_url":"https://api.github.com/repos/aspnet/EntityFramework/issues/4488/events","html_url":"https://github.com/aspnet/EntityFramework/issues/4488","id":131302810,"number":4488,"title":"[Question/Issue] Adding entities with and without keys in the same context. The instance of entity type 'XXXX' cannot be tracked because another instance of this type with the same key is already being tracked.","user":{"login":"danielcirket","id":6743309,"avatar_url":"https://avatars.githubusercontent.com/u/6743309?v=3","gravatar_id":"","url":"https://api.github.com/users/danielcirket","html_url":"https://github.com/danielcirket","followers_url":"https://api.github.com/users/danielcirket/followers","following_url":"https://api.github.com/users/danielcirket/following{/other_user}","gists_url":"https://api.github.com/users/danielcirket/gists{/gist_id}","starred_url":"https://api.github.com/users/danielcirket/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/danielcirket/subscriptions","organizations_url":"https://api.github.com/users/danielcirket/orgs","repos_url":"https://api.github.com/users/danielcirket/repos","events_url":"https://api.github.com/users/danielcirket/events{/privacy}","received_events_url":"https://api.github.com/users/danielcirket/received_events","type":"User","site_admin":false},"labels":[{"url":"https://api.github.com/repos/aspnet/EntityFramework/labels/pri0","name":"pri0","color":"e11d21"},{"url":"https://api.github.com/repos/aspnet/EntityFramework/labels/task","name":"task","color":"d4c5f9"}],"state":"open","locked":false,"assignee":{"login":"ajcvickers","id":1430078,"avatar_url":"https://avatars.githubusercontent.com/u/1430078?v=3","gravatar_id":"","url":"https://api.github.com/users/ajcvickers","html_url":"https://github.com/ajcvickers","followers_url":"https://api.github.com/users/ajcvickers/followers","following_url":"https://api.github.com/users/ajcvickers/following{/other_user}","gists_url":"https://api.github.com/users/ajcvickers/gists{/gist_id}","starred_url":"https://api.github.com/users/ajcvickers/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/ajcvickers/subscriptions","organizations_url":"https://api.github.com/users/ajcvickers/orgs","repos_url":"https://api.github.com/users/ajcvickers/repos","events_url":"https://api.github.com/users/ajcvickers/events{/privacy}","received_events_url":"https://api.github.com/users/ajcvickers/received_events","type":"User","site_admin":false},"milestone":{"url":"https://api.github.com/repos/aspnet/EntityFramework/milestones/18","html_url":"https://github.com/aspnet/EntityFramework/milestones/1.0.0-rc2","labels_url":"https://api.github.com/repos/aspnet/EntityFramework/milestones/18/labels","id":1403248,"number":18,"title":"1.0.0-rc2","description":null,"creator":{"login":"bricelam","id":1226749,"avatar_url":"https://avatars.githubusercontent.com/u/1226749?v=3","gravatar_id":"","url":"https://api.github.com/users/bricelam","html_url":"https://github.com/bricelam","followers_url":"https://api.github.com/users/bricelam/followers","following_url":"https://api.github.com/users/bricelam/following{/other_user}","gists_url":"https://api.github.com/users/bricelam/gists{/gist_id}","starred_url":"https://api.github.com/users/bricelam/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/bricelam/subscriptions","organizations_url":"https://api.github.com/users/bricelam/orgs","repos_url":"https://api.github.com/users/bricelam/repos","events_url":"https://api.github.com/users/bricelam/events{/privacy}","received_events_url":"https://api.github.com/users/bricelam/received_events","type":"User","site_admin":false},"open_issues":27,"closed_issues":152,"state":"open","created_at":"2015-11-09T22:23:36Z","updated_at":"2016-02-05T19:18:43Z","due_on":null,"closed_at":null},"comments":4,"created_at":"2016-02-04T10:21:57Z","updated_at":"2016-02-05T19:19:35Z","closed_at":null,"body":"So, I have a DbSet<T> for which at runtime/startup I want to seed some initial/test data if it doesn't exist.\r\n\r\nHowever i'm running into some issues when adding the first entry with a set key (will be a default value of -1), then trying to add the next item with no Id set to be generated, I get an exception thrown for the key already existing in the dbset.\r\n\r\nFor the entity type I'm using this as a base class:\r\n\r\n```C#\r\npublic abstract class Entity\r\n{\r\n    public virtual int? Id { get; set; }\r\n    public virtual DateTime CreatedDate { get; set; }\r\n    public virtual int CreatedById { get; set; }\r\n    public virtual DateTimeLastModifiedDate { get; set; }\r\n    public virtual int LastModifiedById { get; set; }\r\n    public virtual bool IsDeleted { get; set; }\r\n}\r\n```\r\n\r\nWith the entity as:\r\n\r\n```C#\r\npublic class Country : Entity\r\n{\r\n   public string Name { get; set; }\r\n}\r\n```\r\n\r\n(I have tried this with different combinations of the Id property having the UseSqlServerIdentityColumn() and ValueGeneratedOnAdd() and with both removed (Adding them seemed to make no difference, but wanted to try as many options as possible in case I was missing something).\r\n\r\n```C#\r\npublic static void AddEntityDefaults<T>(this EntityTypeBuilder<T> source) where T : Entity    \r\n{\r\n    source.HasKey(x => x.Id);\r\n    source.Property(x => x.Id).UseSqlServerIdentityColumn();\r\n    source.Property(x => x.Id).ValueGeneratedOnAdd();\r\n    source.Property(x => x.CreatedDate).HasDefaultValue(DateTime.Now).ValueGeneratedOnAdd();\r\n    source.Property(x => x.LastModifiedDate).HasDefaultValue(DateTime.Now).ValueGeneratedOnAddOrUpdate();\r\n    source.Property(x => x.IsDeleted)\r\n        .HasDefaultValue(false)\r\n        .IsRequired();\r\n}\r\n```\r\n\r\nAnd for the 'seeding' I'm using this (Which works perfectly for a single entity OR a number of entities where the Id is null for all items). I have tried wrapping this in a transaction, and running an SQL command to enable then disable identity insert, saving the entity with the Id set before adding the additional items and simply adding them one at a time then saving.\r\n\r\nThis works for adding a single with the Id set to -1:\r\n\r\n```C#\r\nprivate static void InitialiseCountries(this DataContext source)\r\n{\r\n    if (source.Countries.Any())\r\n        return;\r\n\r\n    using (var transaction = source.Database.BeginTransaction())\r\n    {\r\n        source.Database.ExecuteSqlCommand(\"SET IDENTITY_INSERT Country ON\");\r\n\r\n        source.Countries.Add(new Country { Id = -1, Name = \"Unknown\", CreatedById = -1 });\r\n        source.SaveChanges();\r\n\r\n        source.Database.ExecuteSqlCommand(\"SET IDENTITY_INSERT Country OFF\");\r\n        transaction.CommitTransaction();\r\n    }\r\n}\r\n```\r\n\r\nThis works for adding multiple items where the Id is still null (I could use add range for this, but changed it to below to make sure it wasn't me calling add multiple times that was causing the issue):\r\n\r\n```C#\r\nprivate static void InitialiseCountries(this DataContext source)\r\n {\r\n     if (source.Countries.Any())\r\n        return;\r\n\r\n    source.Countries.Add(new Country { Name = \"Unknown\", CreatedById = -1 });\r\n    source.Countries.Add(new Country { Name = \"Test\", CreatedById = -1 });\r\n    source.Countries.Add(new Country { Name = \"Test2\", CreatedById = -1 });\r\n    source.Countries.Add(new Country { Name = \"Test3\", CreatedById = -1 });\r\n    source.SaveChanges();\r\n}\r\n```\r\n\r\nBut this gives me the exception (As mentioned above, tried SaveChanges() before and after the 2nd item is added, and before and after the 2nd ExecuteSqlCommand which makes no difference):\r\n\r\n```C#\r\nprivate static void InitialiseCountries(this DataContext source)\r\n{\r\n    if (source.Countries.Any())\r\n        return;\r\n\r\n    using (var transaction = source.Database.BeginTransaction())\r\n    {\r\n        source.Database.ExecuteSqlCommand(\"SET IDENTITY_INSERT Country ON\");\r\n\r\n        source.Counties.Add(new Country { Id = -1, Name = \"Unknown\", CreatedById = -1 });\r\n        source.SaveChanges();\r\n\r\n        source.Database.ExecuteSqlCommand(\"SET IDENTITY_INSERT Country OFF\");\r\n                \r\n        source.Counties.Add(new Country { Name = \"Test\", CreatedById = -1 }); // <-- The exception happens here.\r\n        source.SaveChanges();\r\n        \r\n        transaction.CommitTransaction();\r\n    }\r\n}\r\n```\r\n\r\nThe exception:\r\n\r\n```\r\nAn exception of type 'System.InvalidOperationException' occurred in EntityFramework.Core.dll but was not handled in user code\r\n\r\nAdditional information: The instance of entity type 'My.Namespace.Entities.Country ' cannot be tracked because another instance of this type with the same key is already being tracked. For new entities consider using an IIdentityGenerator to generate unique key values.\r\n```\r\n\r\n_I'm expecting that this may be something I'm doing incorrectly or should potentially use a different approach, however I've never used EF before this version, so have no prior experience to go on and my Google-foo has failed on this occasion._"},"comment":{"url":"https://api.github.com/repos/aspnet/EntityFramework/issues/comments/180509315","html_url":"https://github.com/aspnet/EntityFramework/issues/4488#issuecomment-180509315","issue_url":"https://api.github.com/repos/aspnet/EntityFramework/issues/4488","id":180509315,"user":{"login":"rowanmiller","id":4741851,"avatar_url":"https://avatars.githubusercontent.com/u/4741851?v=3","gravatar_id":"","url":"https://api.github.com/users/rowanmiller","html_url":"https://github.com/rowanmiller","followers_url":"https://api.github.com/users/rowanmiller/followers","following_url":"https://api.github.com/users/rowanmiller/following{/other_user}","gists_url":"https://api.github.com/users/rowanmiller/gists{/gist_id}","starred_url":"https://api.github.com/users/rowanmiller/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/rowanmiller/subscriptions","organizations_url":"https://api.github.com/users/rowanmiller/orgs","repos_url":"https://api.github.com/users/rowanmiller/repos","events_url":"https://api.github.com/users/rowanmiller/events{/privacy}","received_events_url":"https://api.github.com/users/rowanmiller/received_events","type":"User","site_admin":false},"created_at":"2016-02-05T19:19:35Z","updated_at":"2016-02-05T19:19:35Z","body":"We think moving to min int number will avoid almost every case where you would hit conflicts. Assigning to @ajcvickers to make this change."}}