標籤:
這一章主要介紹EF的使用:
關於EF的擷取在上一章中已經給出了
現在需要建立一個AppModelContext
[DbConfigurationType(typeof(MysqlDbConfiguration))] public partial class AppModelContext : IdentityDbContext<ApplicationUser, CustomIdentityRole, Guid, CustomUserLogin, CustomUserRole, CustomUserClaim> { static AppModelContext() { } public static AppModelContext Create() { return new AppModelContext(); } public AppModelContext() : base("Name=db") { }public DbSet<Vote> Votes { get; set; } public void SetDebugOutput() { this.Database.Log = (s) => Debug.WriteLine(s); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<ApplicationUser>().Property(p => p.PasswordHash).HasMaxLength(200); modelBuilder.Entity<ApplicationUser>().Property(p => p.SecurityStamp).HasMaxLength(200); modelBuilder.Entity<ApplicationUser>().Property(p => p.PhoneNumber).HasMaxLength(50); modelBuilder.Entity<CustomIdentityRole>().Property(p => p.Name).HasMaxLength(128); modelBuilder.Entity<ApplicationUser>().Property(p => p.UserName).HasMaxLength(128); }
其中
public DbSet<Link> Links { get; set; }
這段代碼是用來建立資料表的,資料表的結構在 Link類中建立
關於Link類中的內容:
public class Link { [Key] public int Id { get; set; } [StringLength(50)] [Display(Name="標題")] public string Title { get; set; } [StringLength(500)] [Url] [Display(Name="連結")] public string Url { get; set; } public LinkType Type { get; set; } public int SchoolId { get; set; } public LinkState LinkState { get; set; } public virtual ApplicationUser User { get; set; } public Guid UserId { get; set; } // public LinkType Type { get; set; } public int TypeId { get; set; } }
其中包含主鍵[Key] 字串長度[StringLength(50)] 過濾規則[Url] 以及 顯示名稱 [Display(Name="標題")]
public virtual ApplicationUser User { get; set; } public Guid UserId { get; set; }
是用來定義外鍵
在定義完表結構之後
我們將內容添加到Context中,然後在Package Manager Console 中輸入 Enable-Migration
然後系統會自動產生Migration檔案夾,然後輸入 add-migration Name
再輸入Update-database 就可以更新資料庫,以後每次更改表結構都要add-migration Name 然後Update-database之後 就可以更新表結構,但是如果表中有資料又添加了不可為空白的欄位,是會報錯的。
使用EF可以將類直接映射成表結構,也可以將資料庫的資料直接載入到對象當中,代碼出錯率會大幅度降低,代碼修改成本也會大幅度降低,EF是一個非常優秀的架構
C#部落格隨筆之九:EF架構的使用