【发布时间】:2020-04-15 16:15:13
【问题描述】:
我正在开发一个使用 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);
}
}
每次我运行应用程序时,都会重复行。 编号 39 asd1, id 40 asd2, 编号 41 asd1, 编号 42 asd2, id 43 asd1, id 44 asd2,
你知道为什么会这样吗?
【问题讨论】:
标签: c# asp.net-mvc entity-framework linq