【问题标题】:get the name of a column of an entity [duplicate]获取实体列的名称[重复]
【发布时间】:2021-02-19 09:14:49
【问题描述】:

我正在使用 asp.net core 3.1 和实体框架 6 创建一个网站

我想在代码 c# 中从我的数据库中获取实体列的名称。

[Table("CORPSDEMETIER")]
public partial class CorpsDeMetier : BaseClass
{
    
    [Column("CODE_CORPS_DE_METIER")]
    [StringLength(5)]
    public string CodeCorpsDeMetier { get; set; }

    [Column("LIBELLE_CORPS_DE_METIER")]
    [StringLength(50)]
    public string LibelleCorpsDeMetier { get; set; }

    public IList<EntrepriseCorpsdemetier> EntrepriseCorpsdemetiers { get; set; }
    public IList<ProjetEntrepriseCorpsDeMetier> ProjetEntreprisesCorpsDeMetier { get; set; }

}

我已经看到如何使用这样的 SQL 查询来获取它:

SELECT * FROM sys.columns WHERE object_id = OBJECT_ID( 'CORPSDEMETIER' ) 

但是当我认为我可以在代码中得到它时,我不想再询问数据库。

在这种情况下,我想获得“LIBELLE_CORPS_DE_METIER”

CorpsDeMetier item = new CorpsDeMetier();
string name = item.LibelleCorpsDeMetier. ......;

对不起,我的英语很差,希望你能理解我。 感谢您阅读我。

【问题讨论】:

标签: c# asp.net-core entity-framework-6


【解决方案1】:

您可以使用反射并读取 ColumnAttribute 名称。

 public static class ObjExtenstions
 {
    public static string GetColumnName(this object obj, string name)
    {
        string result = name;

        var property = obj.GetType().GetProperties().FirstOrDefault(x => x.Name.Equals(name));
        if (property != null)
        {
            var columnAttribute = (ColumnAttribute)property.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(ColumnAttribute));
            result = columnAttribute?.Name;
        }

        return result;
    }
 }

用法(如果没有使用 ColumnAttribute 则返回属性名称):

var name = item.GetColumnName(nameof(CorpsDeMetier.LibelleCorpsDeMetier));

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 2014-01-07
    相关资源
    最近更新 更多