无法跟踪实体类型“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 public class SeedData { public static void Initialize(IServiceProvider serviceProvider) { using (var context = new ApplicationDbContext( serviceProvider.GetRequiredService>())) { // 寻找任何电影。if (context.WalletTypes.Any()) { return; } // 数据库已被播种 }
context.WalletTypes.AddRange(
new WalletType
{
TypeId = 1,
TypeTitle = "function1"
},
new WalletType
{
TypeId = 1,
TypeTitle = "function2"
}
);
context.SaveChanges();
}
}
}
///////////////////////////////////// //Program.cs 公共类 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>();
}
那是因为您使用 dame TypeId 添加到 WalletType。您可以将身份设置为自动或手动提供唯一值。
context.WalletTypes.AddRange(
new WalletType
{
TypeId = 1,
TypeTitle = "function1"
},
new WalletType
{
TypeId = 2,
TypeTitle = "function2"
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句