定义实体类型:
定义两个实体Menu和MenuCard,一个menu关联一个menucard,menucard包含对所有menu的引用。
public class Menu
{
public int Id { get; set; } [StringLength(50)]
public string Text { get; set; }
public decimal Price { get; set; }
public DateTime? Date { get; set; }
public MenuCard MenuCard { get; set; }
public int MenuCardId { get; set; }
}
public class MenuCard
{
public int Id { get; set; }
public string Text { get; set; }
public virtual ICollection<Menu> Menus { get; set; }
}
创建数据上下文,新建类MenuContext派生于基类DbContext,使用模型构建器定义各个字段的约束和各表之间的级联关系,需要引用EntityFramework程序集。
public class MenuContext:DbContext
{
public MenuContext():base(GetConnectionString())
{
} /// <summary>
/// Get the connection string to connect database
/// </summary>
/// <returns>connection string</returns>
private static string GetConnectionString()
{
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["CodeFirst"];
return settings.ConnectionString;
} public DbSet<Menu> Menus { get; set; }
public DbSet<MenuCard> MenuCards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Menu>().Property(m => m.Price).HasColumnType("money");
modelBuilder.Entity<Menu>().Property(m => m.Date).HasColumnType("date");
modelBuilder.Entity<Menu>().Property(m => m.Text).HasMaxLength(40).IsRequired();
modelBuilder.Entity<Menu>().HasRequired(m => m.MenuCard).WithMany(c => c.Menus).HasForeignKey(m => m.MenuCardId);
modelBuilder.Entity<MenuCard>().Property(c => c.Text).HasMaxLength(30).IsRequired();
modelBuilder.Entity<MenuCard>().HasMany(c => c.Menus).WithRequired().WillCascadeOnDelete();
}
}
创建数据库,填充数据。数据库初始化实现了IDatabaseInitializer<TContext>接口,这个接口由CreateDatabaseIfNotExists、DropDatabaseAlways和DropDatabaseIfModelChanges实现,新建类MenuCardInitializer
public class MenuCardsInitializer:DropCreateDatabaseAlways<MenuContext>
{
protected override void Seed(MenuContext context)
{
var menuCards = new List<MenuCard>()
{
new MenuCard {
Text ="Soups",Menus=new List<Menu>(){
new Menu {
Text = "Baked Potatoe Soup",Price=4.80m,Date=DateTime.Parse("5/22/2016",System.Globalization.CultureInfo.InvariantCulture)
},
new Menu {
Text="Rib Eye Steak",Price=5.20m,Date=DateTime.Parse("5/21/2016",System.Globalization.CultureInfo.InvariantCulture)
}
}
},
new MenuCard {
Text ="Steaks",Menus=new List<Menu>() {
new Menu {
Text="New York Sirloin Steak",
Price=6.28m,Date=DateTime.Parse("5/20/2016",System.Globalization.CultureInfo.InvariantCulture)},
new Menu {
Text="Rib Eye Steak",Price=7.20m,Date=DateTime.Parse("5/19/2016",System.Globalization.CultureInfo.InvariantCulture)}
}
}
};
menuCards.ForEach(c => context.MenuCards.Add(c));
}
}
在program类中运行:
class Program
{
static void Main(string[] args)
{ //CreateMenus().Wait();
QueryMenu();
} /// <summary>
/// crwate data to test entity framework
/// </summary>
/// <returns></returns>
private static async Task CreateMenus()
{
using (var data = new MenuContext())
{
MenuCard card = data.MenuCards.Create();
card.Text = "Soups";
data.MenuCards.Add(card);
Menu m = data.Menus.Create();
m.Text = "Baked Potato Soup";
m.Price = 4.80m;
m.Date = new DateTime(2016, 5, 22);
m.MenuCard = card;
data.Menus.Add(m);
Menu m1 = data.Menus.Create();
m1.Text = "Cheddar Broccoli Soup";
m1.Price = 5.06m;
m1.Date = new DateTime(2016, 5, 21);
m1.MenuCard = card;
data.Menus.Add(m1);
try
{
data.SaveChanges();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
} private static void QueryMenu()
{
using (var data = new MenuContext())
{
foreach (var card in data.MenuCards)
{
Console.WriteLine(card.Text);
foreach (var menu in card.Menus)
{
Console.WriteLine("{0}-{1:d}", menu.Text, menu.Date);
}
}
}
}
}