【问题标题】:“How to fix ‘The instance of entity type ' cannot be tracked because another instance with the key value '{TypeId: 1}' is already being tracked.“如何修复‘实体类型的实例’无法跟踪,因为键值‘{TypeId: 1}’的另一个实例已经被跟踪。
【发布时间】:2026-02-13 10:20:04
【问题描述】:

无法跟踪实体类型“WalletType”的实例,因为已在跟踪另一个具有键值“{TypeId: 1}”的实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。

//WalletType.cs 公共类 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; }
}

//////////////////////////// //种子数据.cs 公共类种子数据 { 公共静态无效初始化(IServiceProvider serviceProvider) { 使用 (var context = new ApplicationDbContext( serviceProvider.GetRequiredService>())) { // 寻找任何电影。 if (context.WalletTypes.Any()) { 返回; // DB 已播种 }

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

                },

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


            );
            context.SaveChanges();
        }
    }

}

//////////////////////////////// //程序.cs 公开课程序 {

    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>();

}

【问题讨论】:

    标签: asp.net asp.net-core-2.2


    【解决方案1】:

    那是因为您使用 dame TypeId 添加到 WalletType。 您可以将标识设置为自动或手动提供唯一值。

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

    【讨论】: