模型:就是要显示、保存、创建、更新和删除的对象。
Album模型
public class Album
{
public virtual int AlbumId { get; set; }
public virtual int GenreId{get;set;}
public virtual int ArtistId { get; set; }
public virtual string Title { get; set; }
public virtual decimal Price { get; set; }
public virtual string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
//Genre 和Artist 叫导航属性,记录表之间的关系。
}
基架:基架可以为应用程序的创建,读取,更新和删除功能生成所需要的代码模板。简而言之,就是自动创建生成需要的东西。
为什么在实体类中使用virtual :高效的修改跟踪机制,便于EF感知。
DBContext类型
当使用EF的代码优先方法时,需要使用从EF的DbContext类派生出一个类来访问数据库。该派生类具有一个或多个DbSet<T>类型的属性,类型DbSet<T>中的T代表一个想要持久保存的对象,可以把DbSet<T>想象成一个特殊的,可以感知数据的泛型类别,它知道如何在父上下文中加载和保存数据。
public class MvcMusicStore1DBContext : DbContext
{
//name指定数据库的名称
public MvcMusicStore1DBContext() : base("name=MvcMusicStore1DBContext"){
}
public System.Data.Entity.DbSet<MvcMusicStore1.Models.Album> Albums { get; set; }
public System.Data.Entity.DbSet<MvcMusicStore1.Models.Artist> Artists { get; set; }
public System.Data.Entity.DbSet<MvcMusicStore1.Models.Genre> Genres { get; set; }
}
_MigrationHistory表:EF用这个表来跟踪代码优先模型的状态,是模型和数据库保持一致。
数据库初始化器
当使用SetInitializer方法时,需要传递一个IDatabaseInitializer对象,而框架中带有两个对象:DropCreateDatabaseAlways和DropCreateDatabaseIfModelChanges。
DropCreateDatabaseAlways:每次运行都重新创建
DropCreateDatabaseIfModelChanges:当模型发生改变时创建
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{Database.SetInitializer(new MusicStoreDbInitializer());
}
}
public class MusicStoreDbInitializer : DropCreateDatabaseAlways<MvcMusicStore1.Models.MvcMusicStore1DBContext>
{
//在程序运行时添加初始化数据。
protected override void Seed(MvcMusicStore1DBContext context)
{
context.Artists.Add(new Artist() { Name = "Al Di Meola" });
context.Genres.Add(new Genre() { Name = "Jazz" });
context.Albums.Add(new Album()
{
Artist = new Artist() { Name = "Rush" },
Genre = new Genre() { Name = "Rock" },
Price = 9.99m,
Title = "Caravan"
});
base.Seed(context);
}
}