Entity Framework - Capitalizing first property name letter

Viewed 15597

In general, I tend to name my sql database columns using the following camel case convention:

camelCase (notice that the first letter is in lower case).

But when working with C#, I like to name my object's public properties in the following convention:

PascalCase (notice the first is in uppwer case).

Entity Framework's default behaviour is to name the created classes' properties to match their relative column names as they are in the database.

Is there any property in the project/solution level which can be changed in order to solve this issue?

9 Answers

Yes there is. Here you can see the full example:

using System;
using System.Data.Entity;

namespace ConsoleApplication1
{
    class MyDbContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Properties().Configure(c =>
            {
                var name = c.ClrPropertyInfo.Name;
                var newName = char.ToLower(name[0]) + name.Substring(1);
                c.HasColumnName(newName);
            });
        }

        public MyDbCondenxt(string cs) : base(cs)
        {

        }

        public DbSet<MyModel> MyModels { get; set; }

    }

    class Program
    {
        static void Main(string[] args)
        {
            var context = new MyDbContext ("DefaultConnection");
            context.MyModels.Add(new MyModel{SomeText = "hello"});
            context.SaveChanges();

            Console.ReadLine();
        }
    }

    class MyModel
    {
        public int Id { get; set; }
        public string SomeText { get; set; }
    }


}

The property name is "SomeText" and the column name is "someText".

there are ways to do that , some of are already pointed out by others..

i found one class which does that ...

namespace System.Data.Entity.ModelConfiguration.Conventions
{
  /// <summary>
 /// Convention to convert any data types that were explicitly specified, via data     annotations or <see cref="T:System.Data.Entity.DbModelBuilder"/> API,
 ///                 to be lower case. The default SqlClient provider is case   sensitive and requires data types to be lower case. This convention 
///                 allows the <see   cref="T:System.ComponentModel.DataAnnotations.ColumnAttrbiute"/> and <see cref="T:System.Data.Entity.DbModelBuilder"/> API to be case insensitive.
/// 
/// </summary>
public sealed class ColumnTypeCasingConvention : IDbConvention<DbTableColumnMetadata>,   IConvention
{
  internal ColumnTypeCasingConvention()
{
}

[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
void IDbConvention<DbTableColumnMetadata>.Apply(DbTableColumnMetadata tableColumn, DbDatabaseMetadata database)
{
  if (string.IsNullOrWhiteSpace(tableColumn.TypeName))
    return;
  tableColumn.TypeName = tableColumn.TypeName.ToLowerInvariant();
}

} }

explicit implementation of idbconvertion does that thing which you can implement

another one is to

go to solution => and find folder obj/debug/edmxresourcestoembed

there are three files db.csdl , db.msl , db.ssdl edit msl file => you 'll see mapping for each table like as under.

 <EntitySetMapping Name="Address">
  <EntityTypeMapping TypeName="IsTypeOf(AdventureWorksLTModel.Address)">
    <MappingFragment StoreEntitySet="Address">
      <ScalarProperty Name="AddressID" ColumnName="AddressID" />
      <ScalarProperty Name="AddressLine1" ColumnName="AddressLine1" />
      <ScalarProperty Name="AddressLine2" ColumnName="AddressLine2" />
      <ScalarProperty Name="City" ColumnName="City" />
      <ScalarProperty Name="StateProvince" ColumnName="StateProvince" />
      <ScalarProperty Name="CountryRegion" ColumnName="CountryRegion" />
      <ScalarProperty Name="PostalCode" ColumnName="PostalCode" />
      <ScalarProperty Name="rowguid" ColumnName="rowguid" />
      <ScalarProperty Name="ModifiedDate" ColumnName="ModifiedDate" />
    </MappingFragment>
  </EntityTypeMapping>
</EntitySetMapping>

Well you can edit the names in the edmx actually, but everytime you refresh from database it's back to doing it again.

The only viable approach when using edmx type datatypes is to have the correct names (with capital letters) in the tables of the database or it will be to tedious.

You can of cause use link to sql instead, in which case you define your data classes and just supply a name property. But be warned this approach is significantly more manual and is being aborted most places because it requires much more thinking to set up that edmx autogeneration which is a click, click, next approach.

So yes you can edit the names in the edmx, but consider abandoning your camelCasing for tables instead, in hommage to edmx which saves you for a ton on work in return, or your .net autogenerated proxy classes will look wierd, as you know.

Related