【问题标题】:Duplicate row in Seed Initializer种子初始化程序中的重复行
【发布时间】: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


    【解决方案1】:

    您需要确保尚未插入这些行。使用 LINQ 和Any 方法,我也建议简单地使用foreach 循环,这比ForEach 方法更可取和推荐:

    foreach (var item in categories)
    {
        if (!context.Categories.Any(c => c.CategoryId == item.CategoryId))
        {
            context.Categories.AddOrUpdate(item);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      相关资源
      最近更新 更多