I read this question here and it's a bit similar to mine however I couldn't seem to be getting it to work for me.
I'm trying to seed some test data and in this case it's a few Users. However I'd like to seed their addresses also but I can't.
Here is a snippet of my POCOs
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; }
}
In the configuration file it's as follows:
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"
}
);
}
}
}
I've tried a few different ways but after reading that post it made sense to do it like so, however I can't seem to work it.
UPDATE:
As user Igarioshka pointed out the AddOrUpdate method is void and thereby I couldn't return any addresses as my example above.
This is my solution:
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
}}
}
);