基於 ASP.NET Core 2.0 WebAPI 後台架構搭建(4) - EF Core CodeFirst 資料庫建立

來源:互聯網
上載者:User

標籤:enc   last   update   null   ble   個人   date   驗證   url   

  概述

  在 基於 ASP.NET Core 2.0 WebAPI 後台架構搭建(2) - EF Core (MySQL) CodeFirst 資料庫遷移與依賴注入 一文中,我們介紹如何快速以CodeFirst快速搭建資料庫,這一章,我們來完善一下建立資料庫中可以添加的驗證與約束。

  •  微軟爸爸官方文檔:Entity Framework Core

 

  資料庫操作

  (1) 資料庫遷移  add-migration [任一名稱,須唯一] 

  (2) 更新資料庫  update-database 

  (3) 刪除資料庫遷移  remove-migration 

 

  建立模型,分為資料註解和Fluent API,兩者效果一樣,看個人習慣二選一

  (1) 主鍵:按約定,屬性名稱為Id或<type name>Id將配置為實體的鍵,或者加[Key]指定

[Key]public string LicensePlate { get; set; }
 modelBuilder.Entity<Car>().HasKey(c => c.LicensePlate); 

 

  (2) 自增長

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]public DateTime Inserted { get; set; }
modelBuilder.Entity<Blog>().Property(b=>b.Inserted) .ValueGeneratedOnAdd();

 

  (3) 必填或選填屬性

  以下為允許null: string, int?, byte[], decimal?  等

  以下為不允許null: int, decimal, bool  等

[Required]public string Url { get; set; }
modelBuilder.Entity<Blog>().Property(b => b.Url).IsRequired();

 

  (4) 最大長度,僅適用於數組資料類型,如 string 和 byte[] 

[MaxLength(500)]public string Url { get; set; }
modelBuilder.Entity<Blog>().Property(b=>b.Url).HasMaxLength(500);

 

  (5) 自訂資料表格名稱

[Table(“dt_blog”)]public class Blog {}
modelBuilder.Entity<Blog>().ToTable("dt_blog");

 

  (6) 自訂欄名

[Column(“price”)]public DateTime RowVersion { get; set; }

 

 

  (7) decimal精度

[Column(“price”,TypeName ="decimal(12,2)")]public decimal Price { get; set; }
modelBuilder.Entity<Person>().Property(p=>p.Price).HasColumnName("price").HasColumnType("decimal(12,2)");;

 

  (8) 批量修改精度,在OnModelCreating中添加以下代碼

foreach (var property in modelBuilder.Model.GetEntityTypes().SelectMany(t => t.GetProperties().Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?))))        {                property.Relational().ColumnType = "decimal(18,4)";        }    

 

  (9) 並發令牌

(MySQL)
[ConcurrencyCheck]public DateTime RowVersion { get; set; }
(SQLServer)1537269349public byte[] RowVersion { get; set; }
modelBuilder.Entity<Person>().Property(p=>p.RowVersion).IsConcurrencyToken();

 

  (10) 隱藏屬性,指你.NET 實體類中未定義但 EF 核心模型中該實體類型定義

modelBuilder.Entity<Blog>().Property<DateTime>("LastUpdated");

 

  (11) 關係,按照約定,發現的類型上的導覽屬性時,將建立關係。 如果它指向的類型不能將映射為標量類型由當前的資料庫提供者,該屬性被視為一個導覽屬性。

  由於篇幅較長,請參考串連:https://docs.microsoft.com/zh-cn/ef/core/modeling/relationships

public class Blog {public int BlogId { get; set; }public string Url { get; set; }public List<Post> Posts { get; set; } }public class Post {public int PostId { get; set; }public string Title { get; set; }public string Content { get; set; }public int BlogId { get; set; }public Blog Blog { get; set; } } [ForeignKey("BlogForeignKey")] public Blog Blog { get; set; } [InverseProperty("Author")] public List<Post> AuthoredPosts { get; set; } [InverseProperty("Contributor")] public List<Post> ContributedToPosts { get; set; }
modelBuilder.Entity<Post>().HasOne(p=>p.Blog).WithMany(b=>b.Posts);

 

  (12) 索引

modelBuilder.Entity<Blog>().HasIndex(b => b.Url).IsUnique(); modelBuilder.Entity<Person>().HasIndex(p=>new{p.FirstName,p.LastName });

 

  (13) 排除屬性

public class Blog {public int BlogId { get; set; }public string Url { get; set; }public BlogMetadata Metadata { get; set; }} [NotMapped]public class BlogMetadata {public DateTime LoadedFromDatabase { get; set; }}
modelBuilder.Ignore<BlogMetadata>();

 

  (14) 排除類型

public class Blog {public int BlogId { get; set; }public string Url { get; set; } [NotMapped]public DateTime LoadedFromDatabase { get; set; }}
 modelBuilder.Entity<Blog>() .Ignore(b => b.LoadedFromDatabase);

 

 

 

 

基於 ASP.NET Core 2.0 WebAPI 後台架構搭建(4) - EF Core CodeFirst 資料庫建立

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.