我有一个具有一对多关系的学校项目(联系人可以有很多地址)。但我不知道如何正确播种。
在我的数据模型中,联系人有一个virtual ICollection<Address> Addresses
,地址对象有一个外键ContactId
。
所以这是我的种子数据(代码优先),我需要这样做,所以当我在搜索栏中输入联系人姓氏时,它将拉出该联系人的所有信息(地址信息)。
那么我如何在我的种子数据中将这些信息关联起来,这样当你搜索它时,它会提取出它应该是什么?
namespace Success.Data.Migrations
{
public class Seeder
{
public static void Seed(SuccessContext context,
bool seedContacts = true,
bool seedAddresses = true)
{
if (seedContacts) SeedContacts(context);
if (seedAddresses) SeedAddresses(context);
}
private static void SeedContacts(SuccessContext context)
{
context.Contacts.AddOrUpdate(l => l.LastName,
new Contact() { FullName = "Darth Vader", FirstName = "Darth", LastName = "Vader", },
new Contact() { FullName = "Luke Skywalker", FirstName = "Luke", LastName = "Skywalker", },
new Contact() { FullName = "Tony Stark", FirstName = "Tony", LastName = "Stark", },
new Contact() { FullName = "Ricky Bobby", FirstName = "Ricky", LastName = "Bobby", },
new Contact() { FullName = "Trix Rabbit", FirstName = "Trix", LastName = "Rabbit", });
context.SaveChanges();
}
private static void SeedAddresses(SuccessContext context)
{
context.Addresses.AddOrUpdate(h => h.HomeAddress,
new Address() { HomeAddress = "1300 DeathStar", BusinessAddress = "444 Imperial Fleet", PoBox = "PO Box 1335", ContactId = 1, },
new Address() { HomeAddress = "1997 Endor", BusinessAddress = "448 Rebel Fleet", PoBox = "PO Box 1339", ContactId = 2, },
new Address() { HomeAddress = "1224 Malibu Point", BusinessAddress = "657 Stark Industries", PoBox = "PO Box 1337", ContactId = 3, },
new Address() { HomeAddress = "9978 Fast LN.", BusinessAddress = "532 NASCAR Race Track", PoBox = "PO Box 1333", ContactId = 4, },
new Address() { HomeAddress = "9864 Cerial Box LN", BusinessAddress = "8432 Kellog Dr.", PoBox = "PO Box 1338", ContactId = 5, });
context.SaveChanges();
}
}
}