在OnModelCreating期间设置列名称 [英] Set column names during OnModelCreating
问题描述
我目前正在尝试通过设置的属性为表及其列添加前缀.我正在使用Entity Framework Core.我已经正确地为表名添加了前缀,但是我似乎无法为各列弄清楚.我觉得我需要使用反射.
I am currently trying to prefix my tables and their columns via an attribute that is set. I am using Entity Framework Core. I've gotten it right to prefix the table name but I cannot seem to figure it out for the columns. I have a feeling I will need to use reflection.
我放弃了(可能很差)的反思.有人可以设置实体中列的名称吗?
I have left my (probably poor) attempt at reflection in. Does someone have a way of setting the name of a column in an entity?
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
Debugger.Launch();
//Loop though each entity to set table names correctly
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
//Get the custom attributes of the entity
var attributes = entity.ClrType.GetCustomAttributes(true);
//Throw exception if there isn't any custom attribute applied to the class
if (attributes.Length == 0)
throw new ArgumentNullException(nameof(entity), "Entity is missing table prefix.");
//Get the table prefix
var prefix = attributes[0];
//Set the table name
entity.Relational().TableName = prefix + entity.Relational().TableName;
//Loop through all the columns and apply the prefix
foreach (var prop in entity.GetProperties())
{
var propInfo = entity.ClrType.GetProperty(prop.Name);
propInfo.SetValue(entity.ClrType, prefix + prop.Name, null);
}
}
}
推荐答案
它类似于您对表名所做的操作.只需使用 ColumnName 属性:
It's similar to what you did with the table name. Just use the Relational() extension method of IMutableProperty
and ColumnName property:
foreach (var prop in entity.GetProperties())
{
prop.Relational().ColumnName = prefix + prop.Relational().ColumnName;
}
这篇关于在OnModelCreating期间设置列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!