【问题标题】:How to map a column name with spaces in it to a POCO property?如何将包含空格的列名映射到 POCO 属性?
【发布时间】:2015-01-20 15:52:08
【问题描述】:

我正在处理具有包含空格的列名的数据库表,例如“级别描述”。

我无法更改列名。现在我有这个表的实体框架模型类,编译器抱怨这个属性,因为属性名称不能包含空格!

如何在我的类中定义带空格的列?

[Table("StudyLevel")]
public class StudyLevelModel
{
    [Key]
    public byte StudyLevelID { get; set; } 

    // How to map this to the column "Level Description"?
    public string Level Description { get; set; }

    public string SLevelType { get; set; }
    public Nullable<bool> IsActive { get; set; }
    public string ESID { get; set; }
    public string RID { get; set; }
    public byte LevelSearchGroup { get; set; }
}

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    您没有必须让您的模型属性名称与您的表列名称完全匹配;有一个 [Column] 属性,您可以应用它来将属性映射到列:

    [Table("StudyLevel")]
    public class StudyLevelModel
    {
        [Key]
        public byte StudyLevelID { get; set; } 
        [Column("Level Description")]
        public string LevelDescription { get; set; }
        public string SLevelType { get; set; }
        public Nullable<bool> IsActive { get; set; }
        public string ESID { get; set; }
        public string RID { get; set; }
        public byte LevelSearchGroup { get; set; }
    }
    

    【讨论】:

    • @toxic 没问题,只是一个提示 - 您不必将可空布尔值声明为 Nullable&lt;bool&gt;,您可以简单地使用 bool? 作为语法糖。
    • 为了使用 Column 属性,必须使用 System.ComponentModel.DataAnnotations.Schema 添加;
    • 与OP的情况相同。存储过程返回 [Fulfillment Name] 字段,此解决方案对我来说非常有效。感谢您整理出如此清晰的示例。
    • 琐事注意 - 如果您需要为复合键包含 Order(就像使用反映 SQL 视图的模型一样),您必须这样做:[Column(name: "Some Name", Order = 0)] (. ..然后Order = 1Order = 2等...)
    • @vapcguy:好点。如果您无法更改视图并且视图的唯一性由多个列组成,则可能必须使用复合键。
    【解决方案2】:

    使用ColumnAttribute 设置名称:

     [Column(Name="Level Description")]
     public string LevelDescription { get; set; }
    

    【讨论】:

    • 它可以在没有名称的情况下工作,例如 [Column("Level Description")] public string LevelDescription { get;放; }
    • 这就是解决方案。很好,您进行了编辑。您的模型中的属性将是驼峰式(正常),并且数据库中的列名称将满足要求。
    • 琐事注意 - 如果您需要为复合键包含 Order(就像使用反映 SQL 视图的模型一样),您必须这样做:[Column(name: "Some Name", Order = 0)] (. ..then Order = 1, Order = 2, 等等...) 但如上所示,它适用于针对 SQL 表的模型。不过,你不需要Name=,就像@Toxic 说的那样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-07
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    相关资源
    最近更新 更多