“如何修复'实体类型的实例'无法跟踪,因为已经跟踪了另一个键值为'{TypeId:1}'的实例。

时间:2019-09-30 05:01:02

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

无法跟踪实体类型“ 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; }
}

///////////////////////////////// //SeedData.cs  公共类SeedData     {         公共静态无效的Initialize(IServiceProvider serviceProvider)         {             使用(var context = new ApplicationDbContext(                 serviceProvider.GetRequiredService>()))             {                 //寻找任何电影。                 如果(context.WalletTypes.Any())                 {                     返回; // DB已播种                 }

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

                },

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


            );
            context.SaveChanges();
        }
    }

}

///////////////////////////////////////// //Program.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>();

}

1 个答案:

答案 0 :(得分:0)

那是因为您使用dame TypeId添加到WalletType。 您可以将身份设置为自动,也可以手动提供唯一值。

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

                },

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


            );