我不确定我是否了解您的需求,但我认为您的情况是您已经拥有 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();
}
现在只需更新数据库
它有效。