I am trying to link two tables to each other that will be recognised in the database, Customer and Address for example. Where the Address is virtual in the Customer class and pulled through into a list at load to then be stored in the AddressId (at the moment just using the Controller and Views auto created from my classes by VS2013).
Is this possible? I am looking into this as creating SQL DBs just for testing can be long and this is a quick way to set up a backend DB, especially in testing.
Usually I would do this with stored procedures and SQL but wanted to try a code first ran database.
I have a Customer an Address class, and a CustAddInitializer class, however unless I explicitly state the Id of the address class, the address class won't be recognised in the customer table.
Thanks in advance, example code below.
public class Customer
{
[Key]
public int CustomerId { get; set; }
[Required(ErrorMessage = "First name is required")]
[Display(Name = "First Name")]
[MaxLength(30)]
public string FirstName { get; set; }
public int AddressId { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
[Key]
public int AddressId { get; set; }
[Required(ErrorMessage = "Street is required")]
[Display(Name = "Street")]
[MaxLength(30)]
public string Street { get; set; }
}
public class CustAddInitializer : DropCreateDatabaseIfModelChanges<SomeContext>
{
protected override void Seed(SomeContext context)
{
var customers = new List<Customer>
{
new Customer
{
FirstName="Joe"
}
};
customers.ForEach(tmp => context.Customers.Add(tmp));
context.SaveChanges();
var addresses = new List<Address>
{
new Address
{
Street="Joe Street"
}
};
addresses.ForEach(tmp => context.Addresses.Add(tmp));
context.SaveChanges();
}
}
public class SomeContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Address> Addresses { get; set; }
//tables will be created non-plural whenn constructed from code
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}