I am new to ASP.NET and EF but have Ruby MVC experience. I am working on a complex app that has one to many relationships so I created a smaller project that I can play with and test out CodeFirst generation and what could be more fun than testing with a guitar project! All of you musicians out there know about the one to many relationship as in one guitarist owns several guitars and amplifiers. This code works in that it creates the database and tables when I seed it - Just would like some advice on how to do it better and any possible gotchas?
Thanks
namespace GuitarCollector.Models
{
public class Guitarist
{
public Guitarist()
{
Guitars = new List<Guitar>();
Amplifiers = new List<Amplifier>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List<Guitar> Guitars { get; set; }
public List<Amplifier> Amplifiers { get; set; }
}
public class Guitar
{
//Primary Key
public int Id { get; set; }
//Foreign Key
public int GuitaristId { get; set; }
public int YearOfManufacture { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string Finish { get; set; }
public string SerialNumber { get; set; }
public double AppraisedValue { get; set; }
Guitarist Guitarist { get; set; }
}
public class Amplifier
{
//Primary Key
public int Id { get; set; }
//Foriegn Key
public int GuitaristId { get; set; }
public int YearOfManufacture { get; set; }
public int Wattage { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string SerialNumber { get; set; }
public double AppraisedValue { get; set; }
public Guitarist Guitarist { get; set; }
}
}
namespace GuitarCollector.DAL { public class GuitaristContext : DbContext {
public DbSet<Guitarist> Guitarists { get; set; }
public DbSet<Guitar> Guitars { get; set; }
public DbSet<Amplifier> Amplifiers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)You may need to decorate your FK fields withForeignKey("<propName>")attributes where<propName>is the navigation property of the relationship. If you don't plan on accessing the FK ID fields in you application, you can omit them from your model