FreeSql (三十五)CodeFirst 自定義特性


比如項目內已經使用了其它 orm,如 efcore,這樣意味着實體中可能存在 [Key],但它與 FreeSql [Column(IsPrimary = true] 不同。

Q: FreeSql 實體特性為啥這么別扭?

A: 為了考慮一致性用法,全部封裝在 ColumnAttribute 下,這樣用戶使用起來,不用到處 using 或者 回憶特性應該用哪個名字,如自增 [Column(IsIdentity = true)] 即可。

FreeSql 提供 AOP 自定義特性功能,實現與多個 orm 共同擁有一套實體特性,可避免重復定義特性。

以下的示例代碼,FreeSql 使用 EFCore 的實體特性。

v1.4.0+ 已自動識別 EFCore 實體特性 Key/Required/NotMapped/MaxLength/StringLength/DatabaseGenerated/Table/Column

fsql.CodeFirst.ConfigEntity<ModelAopConfigEntity>(a => a.Property(b => b.pkid).IsPrimary(true));

fsql.Aop.ConfigEntity = (s, e) => {
  var attr = e.EntityType.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.TableAttribute), false).FirstOrDefault() as System.ComponentModel.DataAnnotations.Schema.TableAttribute;
  if (attr != null)
    e.ModifyResult.Name = attr.Name;
};
fsql.Aop.ConfigEntityProperty = (s, e) => {
  if (e.Property.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.KeyAttribute), false).Any())
    e.ModifyResult.IsPrimary = true;
};

[System.ComponentModel.DataAnnotations.Schema.Table("xxx")]
class ModelAopConfigEntity {
  [System.ComponentModel.DataAnnotations.Key]
  [Column(IsPrimary = false)]
  public int pkid { get; set; }
}

就這樣,FreeSql 的實體特性就可以和 EFCore 那樣設定了。其他自增、樂觀鎖等,依葫蘆畫瓢便是。

優先級

數據庫特性 > 實體特性 > FluantApi(配置特性) > Aop(配置特性)

系列文章導航


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM