ここでこの質問を読みましたが、私のものと少し似ていますが、うまく機能していないようです。
私はいくつかのテスト データをシードしようとしていますが、この場合は数人のユーザーです。ただし、アドレスもシードしたいのですが、できません。
これが私のPOCOのスニペットです
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string Headline { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public virtual ICollection<Phonenumber> Phonenumbers { get; set; }
public virtual ICollection<Email> Emails { get; set; }
public virtual ICollection<Position> Positions { get; set; }
}
public class Address
{
public string Id { get; set; }
public string StreetName { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
public int Cycle { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
構成ファイルでは、次のようになっています。
internal sealed class Configuration : DbMigrationsConfiguration<CWS.Models.ConnectoDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(CWS.Models.ConnectoDbContext 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.Users.AddOrUpdate(u => u.UserId,
new User
{
Username = "Blackstallion",
FirstName = "Gilbert",
LastName = "Johnson",
Password = "3fZ45SDF",
Headline = "Novice",
Addresses = new List<Address> { context.Addresses.AddOrUpdate(a => a.Id,
new Address
{
StreetName = "asd",
ZipCode = "123",
Country = "abc",
Cycle = 2
});
}},
new User
{
Username = "Qaus",
FirstName = "Jon",
LastName = "Orton",
Password = "1564as5F",
Headline = "Novice"
}
);
}
}
}
私はいくつかの異なる方法を試しましたが、その投稿を読んだ後、そのようにするのは理にかなっていますが、うまくいかないようです.
更新:
ユーザーIgarioshkaが指摘したように、AddOrUpdate メソッドは無効であるため、上記の例のようにアドレスを返すことができませんでした。
これが私の解決策です:
context.Users.AddOrUpdate(u => u.UserId,
new User
{
Username = "Bob",
FirstName = "John",
LastName = "Doe",
Password = "123",
Headline = "Elite",
Addresses = new List<Address>{
new Address
{
Id = "1",
StreetName = "John's Street",
ZipCode = "1234",
Country = "AB",
Cycle = 2
},
new Address
{
Id = "2",
StreetName = "John's Work",
ZipCode = "1234",
Country = "AB",
Cycle = 3
},
new Address
{
Id = "3",
StreetName = "John's Super Secret Street",
ZipCode = "0000",
Country = "AB",
Cycle = 44
}}
}
);