博客
关于我
[EFCore]EntityFrameworkCore Code First 当中批量自定义列名
阅读量:442 次
发布时间:2019-03-06

本文共 2122 字,大约阅读时间需要 7 分钟。

在使用.NET CORE 进行 Web 开发的时候会考虑到使用不同数据库的情况,并且在每种数据库建立表结构的时候会采用不同的命名规则。之前的解决方法是使用 [ColumnAttribute] 或者 [TableAttribute] 这种特性来显式标注不同的列名。

[Table("bas_stock_address")]public class BasStockAddress : FullAuditedEntity
{ ///
/// 仓库ID /// [Column("stock_id")] public int StockId { get; set; } ///
/// 备注 /// [Column("remark")] [StringLength(200)] public string Remark { get; set; }}

这种情况的话就很尴尬,如果实体一多,就要对每个属性进行标注的话,工作量确实会很大。

这个时候就可以使用 Conventions 来处理这种情况,如果是 EntityFramework 6.x 的话可以使用:

提到的方法来进行操作。

如果是 EntityFrameworkCore 的话可以通过 ModelBuilder.Model.GetEntityTypes() 获得所有实体对象的类型以及他的相关属性,并且使用 Relational() 方法来获得实体对象的 Annotation ,这样就可以对生成的表结构进行统一的配置。

public class ApplicationDbContext : IdentityDbContext
{ public ApplicationDbContext(DbContextOptions
options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); foreach(var entity in builder.Model.GetEntityTypes()) { // 覆写表名 entity.Relational().TableName = entity.Relational().TableName.ToSnakeCase(); // 覆写列名 foreach(var property in entity.GetProperties()) { property.Relational().ColumnName = property.Name.ToSnakeCase(); } foreach(var key in entity.GetKeys()) { key.Relational().Name = key.Relational().Name.ToSnakeCase(); } foreach(var key in entity.GetForeignKeys()) { key.Relational().Name = key.Relational().Name.ToSnakeCase(); } foreach(var index in entity.GetIndexes()) { index.Relational().Name = index.Relational().Name.ToSnakeCase(); } } }}public static class StringExtensions { public static string ToSnakeCase(this string input) { if (string.IsNullOrEmpty(input)) { return input; } return Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower(); }}

这里主要的就是 ToSnakeCase 这个扩展方法,他将 NameSnake 这种形式的名称替换为 name_snake。

转载地址:http://ekryz.baihongyu.com/

你可能感兴趣的文章
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx: [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx:objs/Makefile:432: recipe for target ‘objs/src/core/ngx_murmurhash.o‘解决方法
查看>>
Nginx、HAProxy、LVS
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx中使用expires指令实现配置浏览器缓存
查看>>
nginx中配置root和alias的区别
查看>>
nginx主要流程(未完成)
查看>>
Nginx之二:nginx.conf简单配置(参数详解)
查看>>
Nginx从入门到精通
查看>>
Nginx代理websocket配置(解决websocket异常断开连接tcp连接不断问题)
查看>>
Nginx代理初探
查看>>
nginx代理地图服务--离线部署地图服务(地图数据篇.4)
查看>>
Nginx代理外网映射
查看>>
Nginx代理模式下 log-format 获取客户端真实IP
查看>>
Nginx代理解决跨域问题(导致图片只能预览不能下载)
查看>>
Nginx代理访问提示ERR_CONTENT_LENGTH_MISMATCH
查看>>
Nginx代理配置详解
查看>>
Nginx代理静态资源(gis瓦片图片)实现非固定ip的url适配网络环境映射ip下的资源请求解决方案
查看>>