我有一个表 A 和一个表 B,它们之间的关系如下:
表A
Id
...
表B
Id
TableA_Id (foreign key table A)
我首先使用实体框架代码并激活了迁移。
我想做的是进行迁移,为表 B 的每条现有记录在表 A 中添加一条记录,然后在表 B 中添加对新表 A 行的外键引用。强>
我使用了以下命令并创建了一个空迁移:
Add-Migration <NameOfMyMigration>
这导致了以下代码:
public partial class NameOfMyMigration : DbMigration
{
public override void Up()
{
// This is where I want to write code that adds records
}
public override void Down()
{
}
}
最佳答案
我不确定我是否理解你的需求,但我认为你的情况是你已经有 Code First 项目并且已经有充满数据的数据库,现在你想添加新表所以首先我试着联系你情况:
public class ApplicationDbContext : DbContext
{
public DbSet<ClassB> BList { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public class ClassB
{
public ClassB()
{
BId = Guid.NewGuid().ToString();
}
[Key]
public string BId { get; set; }
}
在种子方法中:
protected override void Seed(ApplicationDbContext 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.BList.AddOrUpdate(
new ClassB { BId = Guid.NewGuid().ToString() },
new ClassB { BId = Guid.NewGuid().ToString() },
new ClassB { BId = Guid.NewGuid().ToString() }
);
}
然后添加迁移 和更新数据库 现在我有一个名为 ClassBs 的表,有 3 行 然后创建 ClassAs 表:
public class ClassA
{
public ClassA()
{
AId = Guid.NewGuid().ToString();
}
[Key]
public string AId { get; set; }
}
并像以前一样将 DbSet 添加到上下文中:
public DbSet<ClassA> AList { get; set; }
在种子方法中:
context.AList.AddOrUpdate(
new ClassA { AId = Guid.NewGuid().ToString() },
new ClassA { AId = Guid.NewGuid().ToString() },
new ClassA { AId = Guid.NewGuid().ToString() }
);
现在我有两个像你一样具有一对多关系的表 最后,我现在可以逐行编辑 ClassB 表了。 种子方法:
protected override void Seed(ApplicationDbContext 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.
//
var BArray = context.BList.ToArray();
var AArray = context.AList.ToArray();
for (int i = 0; i < BArray.Length; i++)
{
if (BArray.Length == AArray.Length)
{
BArray[i].AID = AArray[i].AId;
}
}
context.SaveChanges();
}
现在只需更新数据库
它有效。
关于c# - 使用 Entity Framework CF 迁移添加记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34531268/