我正在开发一个使用ASP.NET MVC和实体框架(代码优先)的应用程序。我在复制数据库中的条目时遇到了问题-我希望数据库中的数据只有在它们被删除(和迁移之后)时才会得到补充。
我有一个模型:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
}在DAL文件夹MyContext.cs中:
public class MyContext: DbContext
{
public MyContext() : base("MyContext")
{ }
static MyContext()
{
Database.SetInitializer<MyContext>(new MyInitializer());
}
public DbSet<Category> Categories { get; set; }
}在DAL文件夹MyInitializer.cs中:
public class MyInitializer : MigrateDatabaseToLatestVersion<MyContext, Configuration>
{
public static void SeedMyData(MyContext context)
{
var categories = new List<Category>
{
new Category() { CategoryId = 1, Name = "asd1" },
new Category() { CategoryId = 2, Name = "asd2" }
};
categories.ForEach(x => context.Categories.AddOrUpdate(x));
context.SaveChanges();
}
}在Migrations文件夹Configuration.cs.cs中:
public sealed class Configuration : DbMigrationsConfiguration<MyApp.DAL.MyContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "MyApp.DAL.MyContext";
}
protected override void Seed(MyApp.DAL.MyContext context)
{
MyInitializer.SeedMyData(context);
}
}每次我运行app - row都是重复的。id 39 asd1,id 40 asd2,id 41 asd1,id 42 asd2,id 43 asd1,id 44 asd2,
你知道为什么会发生这样的事情吗?
发布于 2020-04-16 00:21:31
您需要确保尚未插入这些行。使用LINQ和Any方法,我也建议简单地使用foreach循环,它比ForEach方法更可取和推荐:
foreach (var item in categories)
{
if (!context.Categories.Any(c => c.CategoryId == item.CategoryId))
{
context.Categories.AddOrUpdate(item);
}
}https://stackoverflow.com/questions/61233524
复制相似问题