c# - 在代码迁移中如何使用LINQ将一张表中的数据插入到其自身上?

标签 c# linq azure

我正在关注 msft azure 上的教程,它需要自动生成四个字段。我需要添加四个字段,然后重新插入所有数据,以便可以使用代码迁移自动生成? https://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-use-existing-sql-database/

我会在这里放什么?

protected override void Seed(CIMSMobileService.Models.CIMS_Mobile_Service context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }

最佳答案

您应该将其添加到您的模型中,然后添加迁移,它将生成在数据库中创建这些字段的命令 - 然后您可以播种数据。如果您手动添加它们,则您没有使用数据迁移,并且当您将来想要向模型添加字段时,事情将开始变得不同步。

编辑 根据下面提到的文章,他们实际上更改了模型,然后使用初始化程序 (ClearDatabaseSchemaIfModelChanges) 删除所有表内容并使用新架构重新创建表,并使用此处指定的数据查看它

 public class ExistingInitializer : ClearDatabaseSchemaIfModelChanges
    {
        protected override void Seed(ExistingContext context)
        {
            List orders = new List
            {
                new Order { OrderId = 10, Item = "Guitars", Quantity = 2, Id = Guid.NewGuid().ToString()},
                new Order { OrderId = 20, Item = "Drums", Quantity = 10, Id = Guid.NewGuid().ToString()},
                new Order { OrderId = 30, Item = "Tambourines", Quantity = 20, Id = Guid.NewGuid().ToString() }
            };

            List customers = new List
            {
                new Customer { CustomerId = 1, Name = "John", Orders = new Collection {
                    orders[0]}, Id = Guid.NewGuid().ToString()},
                new Customer { CustomerId = 2, Name = "Paul", Orders = new Collection {
                    orders[1]}, Id = Guid.NewGuid().ToString()},
                new Customer { CustomerId = 3, Name = "Ringo", Orders = new Collection {
                    orders[2]}, Id = Guid.NewGuid().ToString()},
            };

            foreach (Customer c in customers)
            {
                context.Customers.Add(c);
            }

            base.Seed(context);
        }
    }

关于c# - 在代码迁移中如何使用LINQ将一张表中的数据插入到其自身上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34641973/

相关文章:

Azure 角色失败通知

c# - MySQL插入查询异常

c# - CSS 中的 Razor 循环

c# - 通过 Id 和名称获取下一个和上一个 sql 行,EF?

c# - Linq Contains() 是否检查 HashSet?

azure - 获取 PnPUnifiedGroup : Code: Authorization_RequestDenied

c# - 如何在 C# 中保存此表?

c# - 从 C# 创建 COM 索引属性?

c# - Linq - 如何聚合另一个查询的结果

powershell - Set-AzureSubscription 出错 - ForbiddenError : The server failed to authenticate the request.