gpt4 book ai didi

asp.net-core - 使用 EFcore/ASP.net core 更新查找表中的数据的正确方法?我是用种子方法还是其他方法来做到这一点?

转载 作者:行者123 更新时间:2023-12-02 19:43:40 24 4
gpt4 key购买 nike

现在我正在开发中,并使用下面的代码来播种查找表。但是一旦投入生产,我想添加额外的数据,我该怎么做?我是否在播种方法中使用某种 AddOrUpdate (不在核心中)?编写 SQL 脚本?

 private static async Task SeedRfReportStateTypesAsync(PwdrsContext pwdrsContext)
{
if (pwdrsContext.RfReportStateTypes.Any())
{
return;
}

List<RfReportStateType> rfReportStateTypes = new List<RfReportStateType>()
{
new RfReportStateType() { Name = "Draft", UpdatedBy = "SYSTEM", UpdatedOn = DateTime.Now}, //4
new RfReportStateType() { Name = "Review", UpdatedBy = "SYSTEM", UpdatedOn = DateTime.Now}, //3
new RfReportStateType() { Name = "Stage", UpdatedBy = "SYSTEM", UpdatedOn = DateTime.Now}, //2
new RfReportStateType() { Name = "Prod", UpdatedBy = "SYSTEM", UpdatedOn = DateTime.Now} //1
};

pwdrsContext.RfReportStateTypes.AddRange(rfReportStateTypes);
await pwdrsContext.SaveChangesAsync();
}

最佳答案

您当前的播种方式已被弃用。如果您将播种处理为 you're supposed to ,然后种子数据的插入、更新等由 EF Core 自动处理。现在可以在您的上下文中通过 OnModelCreating 中的流畅配置来完成:

modelBuilder.Entity<RfReportStateType>().HasData(
new RfReportStateType { Id = 4, Name = "Draft" },
new RfReportStateType { Id = 3, Name = "Review" },
new RfReportStateType { Id = 2, Name = "Stage" },
new RfReportStateType { Id = 1, Name = "Prod" }
);

一些注释。首先,您必须包含 id。这样 EF Core 就知道要插入、更新或删除哪些项目。新的 ID 将被插入,已删除的 ID 将被删除,并且任何现有的 ID 将被更新。由于 id 已知,它还使得创建关系等成为可能。其次,像 UpdatedOn 这样的事情应该通过 auto-generated value 来处理。 ,而不是在种子数据中指定,否则它将在每次运行时触发更新,因为 DateTime.Now 总是不同的,一次运行到下一次运行。这样,您还可以指定是否仅在添加或更新时生成它,使其非常适合创建/更新日期等内容。一般来说,您的种子数据应仅包含静态值,以便仅当您专门更改这些值之一时才会触发更新。第三,如果您愿意,您可以包含 UpdatedBy ,但是通过列上的默认值可能会更好地处理,即它是 SYSTEM ,除非传递了更具体的内容。

关于asp.net-core - 使用 EFcore/ASP.net core 更新查找表中的数据的正确方法?我是用种子方法还是其他方法来做到这一点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59721251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com