public class Country
{
public int Id { get; set; }
public string Name { get; set; }
public string LongName { get; set; }
public string Description { get; set; }
public List<State> States{ get; set; }
}
public class State
{
public int Id { get; set; }
public string Name { get; set; }
public string LongName { get; set; }
// public List<City> { get; set; }
}
Now we deine a DBContext that looks like :
public class CamAccess : DbContext
{
public DbSet<Country> Countrys { get; set; }
public DbSet<State> States { get; set; }
public DbSet<City> Citys { get; set; }
}
This is all we need to do and we when we write some Linq code to use Countrys as in:
public List<Country> GetCountrys()
{
CamAccess camdc = new CamAccess();
Database.SetInitializer<CamAccess>(new CamaccessInitializer());
List<Country> countrys = camdc.Countrys.ToList();
return countrys;
}
Then we have the tables Country and States generated for us including the Foreign keys. This will look something like this:
Note the call to Database.SetInitializer as this is great as it lets us not only recreate the tables as the model changes but populate the tables with data as the class looks like:
public class CamaccessInitializer : DropCreateDatabaseIfModelChanges<CamAccess>
{
protected override void Seed(CamAccess context)
{
Country c = new Country();
c.Name = "USA";
c.LongName = "United States";
context.Countrys.Add(c);
base.Seed(context);
}
}
0 comments:
Post a Comment