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

好比项目内已经使用了其它 orm,如 efcore,这样意味着实体中可能存在 [Key],但它与 FreeSql [Column(IsPrimary = true] 不一样。html

Q: FreeSql 实体特性为啥这么别扭?sql

A: 为了考虑一致性用法,所有封装在 ColumnAttribute 下,这样用户使用起来,不用处处 using 或者 回忆特性应该用哪一个名字,如自增 [Column(IsIdentity = true)] 便可。数据库

FreeSql 提供 AOP 自定义特性功能,实现与多个 orm 共同拥有一套实体特性,可避免重复定义特性。lua

如下的示例代码,FreeSql 使用 EFCore 的实体特性。code

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 那样设定了。其余自增、乐观锁等,依葫芦画瓢即是。orm

优先级

数据库特性 > 实体特性 > FluantApi(配置特性) > Aop(配置特性)htm

系列文章导航