简体   繁体   中英

Entity Framework and database column names

I'm trying to modify a POCO T4 template to include the name of the column in the database that corresponds to each property. For legacy reasons, our database tables are 8.3, and our columns are max 10 characters, so things tend to get abbriviated. Being able to quickly look up which column a given property corresponds to will be a big help.

Given that, I have no clue how to go about doing this. I'm comfortable with the idea of editing the T4 template, I just don't know how to retreive the column name from an EdmProperty object.

Can anyone point me in the right direction?

I've already discussed this in some other answer but I can't find it know. The problem is that to get this information you need to browse MSL part of the mapping - the part where columns are mapped to properties. Unfortunately whole API for MSL metadata items is internal (I think one goal for future EF release is to make it public). When you have T4 template for class generation you normally work with CSDL - that is entity description and it contains only information you see in the EDMX diagram and property window for entities.

I won't say this is the best way about solving this problem, but this is how I did it. I needed to be able to retrieve the the column names in plaintext for binding to BoundField asp controls, and that wasn't baked into the EF template.

So, I added this bit of code which just loads the "simple properties", ie: the column names, to allow me to do that. It adds a struct to the "table" object called "ColumnNames" and exposes the column names as const strings.

<#
    if (simpleProperties.Any())
    {
#>
    public struct ColumnName 
    {
  <# 
      foreach (var simpleProperty in simpleProperties)
      {
  #>
      public const string <#= simpleProperty #> = "<#= simpleProperty #>";
  <# 
      }
  #>
  }
<#  }
#>
}

I placed this before this bit of code in the T4 template that generates the individual files under the edmx file in the solution:

<#
    EndNamespace(code);
}

That will create code that looks like this:

public partial class JobPosting
{
    public int PositionRowId { get; set; }
    public System.Guid PositionRelatedGuid { get; set; }

    public struct ColumnName 
    {
        public const string PositionRowId = "PositionRowId";
        public const string PositionRelatedGuid = "PositionRelatedGuid";
    }
}

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM