假设我们有一个简单的数据库表3750其中有记录;
| Id | Age | FullName |
|------|-----|-----------------|
| 1 | 50 | Michael Jackson |
| 2 | 42 | Elvis Presley |
| 3 | 48 | Whitney Houston |
| ... | ... | ... |
| 3750 | 57 | Prince |
我们希望使用自动生成的方法在数据库中创建此表Configuration.cs
文件及其Seed()
method.
protected override void Seed(OurDbContainer context)
{
context.GreatestSingers.AddOrUpdate(
p => p.Id,
new GreatestSinger { Id = 1, Age = 50, FullName = "Michael Jackson" },
new GreatestSinger { Id = 2, Age = 42, FullName = "Elvis Presley" },
new GreatestSinger { Id = 3, Age = 48, FullName = "Whitney Houston" }
);
}
这是你应该做的。3750 times!
但你的数据中已经有了这些数据现有数据库表。所以我们可以用这个existing要创建的数据Seed()
codes.
在...的帮助下SQL 字符串连接;
SELECT
CONCAT('new GreatestSinger { Id = ', Id ,', Age = ', Age ,', FullName = "', FullName ,'" },')
FROM GreatestSinger
将为我们提供创建所需的所有代码3750数据行。
只需将其复制/粘贴到Seed()
方法。并从包管理器控制台;
Add-Migration SeedDBwithSingersData
Update-Database