Search code examples
asp.netasp.net-core-2.2

“How to fix ‘The instance of entity type ' cannot be tracked because another instance with the key value '{TypeId: 1}' is already being tracked.


The instance of entity type 'WalletType' cannot be tracked because another instance with the key value '{TypeId: 1}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

//WalletType.cs public class WalletType

{
    public WalletType()
    {

    }
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int TypeId { get; set; }


    [MaxLength(150)]
    public string TypeTitle { get; set; }



    public virtual ICollection<Wallet> Wallets { get; set; }
}

//////////////////////////////// //SeedData.cs public class SeedData { public static void Initialize(IServiceProvider serviceProvider) { using (var context = new ApplicationDbContext( serviceProvider.GetRequiredService>())) { // Look for any movies. if (context.WalletTypes.Any()) { return; // DB has been seeded }

            context.WalletTypes.AddRange(
                new WalletType
                {
                    TypeId = 1,
                    TypeTitle = "function1"

                },

                new WalletType
                {
                    TypeId = 1,
                    TypeTitle = "function2"
                }


            );
            context.SaveChanges();
        }
    }

}

/////////////////////////////////////// //Program.cs public class Program {

    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;

            try
            {
                var context = services.
                    GetRequiredService<ApplicationDbContext>();
                context.Database.Migrate();
                SeedData.Initialize(services);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred seeding the DB.");
            }
        }

        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();

}

Solution

  • That's because you add to WalletType with the dame TypeId. You can either set identity to auto or provide unique value manually.

     context.WalletTypes.AddRange(
                    new WalletType
                    {
                        TypeId = 1,
                        TypeTitle = "function1"
    
                    },
    
                    new WalletType
                    {
                        TypeId = 2,
                        TypeTitle = "function2"
                    }
    
    
                );