首页 > 数据库技术 > 详细

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

时间:2019-09-17 10:41:43      阅读:136      评论:0      收藏:0      [点我收藏+]

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

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

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

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

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

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(配置特性)

系列文章导航

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

原文:https://www.cnblogs.com/FreeSql/p/11531576.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!