EntityFrameworkCore Code First 当中批量自定义列名

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
[Table("bas_stock_address")]
public class BasStockAddress : FullAuditedEntity<int, User>
{
	/// <summary>
	/// 集团ID
	/// </summary>
	[Column("group_id")]
	public int? GroupId { get; set; }
	/// <summary>
	/// 仓库ID
	/// </summary>
	[Column("stock_id")]
	public int StockId { get; set; }
	/// <summary>
	/// 地址ID
	/// </summary>
	[Column("address_id")]
	public int? AddressId { get; set; }
	/// <summary>
	/// 详情地址
	/// </summary>
	[Column("complete_address")]
	[StringLength(200)]
	public string CompleteAddress { get; set; }
	/// <summary>
	/// 运输方式
	/// </summary>
	[Column("transport_method_id")]
	public int? TransportMethodId { get; set; }
	/// <summary>
	/// 联系人
	/// </summary>
	[Column("contact_person")]
	[StringLength(20)]
	public string ContactPerson { get; set; }
	/// <summary>
	/// 联系电话
	/// </summary>
	[Column("phone")]
	[StringLength(50)]
	public string Phone { get; set; }
	/// <summary>
	/// 物流公司
	/// </summary>
	[Column("logistics_company")]
	[StringLength(50)]
	public string LogisticsCompany { get; set; }
	/// <summary>
	/// 是否默认
	/// </summary>
	[Column("is_default")]
	public bool? IsDefault { get; set; }
	/// <summary>
	/// 备注
	/// </summary>
	[Column("remark")]
	[StringLength(200)]
	public string Remark { get; set; }

	[ForeignKey("StockId")]
	public BasStock BasStock { get; set; }
}

这种情况的话就很尴尬,如果实体一多,就要对每个属性进行标注的话,工作量确实会很大。 这时候就需要 Conventions 了,在 Entity Framework 6 可以这样来操作: https://msdn.microsoft.com/en-us/library/jj819164(v=vs.113).aspx 而在 EntityFramework Core 当中则是使用 ModelBuilder.Model.GetEntityTypes() 方法来实现。 该方法可以获得所有实体对象的类型,我们只需要对起进行遍历操作,并且使用 Relational() 扩展方法来获得对象的 Annotation ,这样就可以对要生成的表结构的 TableName/ColumnName 来进行操作了。 这里使用 这个例子 来进行示范:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>  
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        foreach(var entity in builder.Model.GetEntityTypes())
        {
            // Replace table names
            entity.Relational().TableName = entity.Relational().TableName.ToSnakeCase();

            // Replace column names            
            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; }

        var startUnderscores = Regex.Match(input, @"^_+");
        return startUnderscores + Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower();
    }
}
Built with Hugo
主题 StackJimmy 设计