我正在使用 ASP.NET MCV4、EF6、Code-First 模型开展一个学校项目。现在,我想知道如何用示例数据填充数据库。我检查了migrations
,但我不想弄乱数据库结构。我只想插入数据,我试过这个:
namespace Autokereskedes.Models
{
public class _SampleData : DropCreateDatabaseIfModelChanges<AutoDb>
{
protected override void Seed(AutoDb context)
{
new Autokereskedes.Models.SampleData.Users().List().ForEach(u=>context.Users.Add(u));
new Autokereskedes.Models.SampleData.Cars().List().ForEach(c => context.Cars.Add(c));
}
}
}
namespace Autokereskedes.Models.SampleData
{
public class Users
{
public List<User> List()
{
var crypto = new SimpleCrypto.PBKDF2();
var salt = Autokereskedes.Controllers.AccountController.PasswordSalt;
return new List<User>
{
new User {
UserId = Guid.NewGuid(),
Email = "admin@autoker.hu",
Password = crypto.Compute("admin",salt),
Phone = "+36 20 XXX YYZZ",
Banned = false,
Country = "Hungary",
City = "Szeged",
Street = "DivisonByZero street 1/0",
ZipCode = 1100,
RegistrationDate = DateTime.Now
},
new User {
UserId = Guid.NewGuid(),
Email = "user@autoker.hu",
Password = crypto.Compute("user",salt),
Phone = "+36 20 XXX YYZZ",
Banned = false,
Country = "Hungary",
City = "Szeged",
Street = "DivisonByZero street 2/0",
ZipCode = 1100,
RegistrationDate = DateTime.Now
}
};
}
}
}
它正在工作,我想。但是我应该如何插入具有外键的数据呢?我看到了一个教程,其中他们为所有 List<>-s 使用了一个文件,并且在外键字段中使用了类似这样的内容:Genre = genres.Single(g => g.Name == "Jazz")
. 我现在真的无法复制。
namespace Autokereskedes.Models.SampleData
{
public class Cars
{
public List<Car> List()
{
return new List<Car>
{
new Car {
CarId = Guid.NewGuid(),
DepoId = now what
},
new Car {
}
};
}
}
}