0

I typically work with my DBA to design my database tables before I begin developing. In nearly all instances, I use the varchar datatype for storing strings in my SQL database.

When I use EF Power Tools to generate my model classes, the column names and lengths get generated correctly, but I always have to go back in and specify HasColumnType("varchar"); because by default everything is nvarchar (I know this by looking at the queries EF generates and the sitautions where it needs to CAST() to varchar).

Is there any way I can generate my model classes from my database and have EF know the correct data types (varchar vs nvarchar)? Meaning, is there anyway I can auto generate my C# model class for my varchar(50) column to show as:

this.Property(t => t.MyColumn)
                .HasMaxLength(50)
                .HasColumnType("varchar");  

Thank you.

Bert Wagner
  • 851
  • 1
  • 11
  • 23
  • Is there any specific reason you need it to be varchar? You would be interested in looking at this other question and it's first answer: http://stackoverflow.com/questions/144283/what-is-the-difference-between-varchar-and-nvarchar – T. Sar Nov 04 '15 at 15:39
  • @ThalesPereira Because I am not using unicode in my application. EDIT: I see your edited link now, I still am not interested in using nvarchar; on a reporting database with 100 millions of entries, the space does add up especially when I know I will not be needing to support unicode. – Bert Wagner Nov 04 '15 at 15:41
  • @BertWagner, yes but is there any detriment to you to have them as NVARCHAR? – Moo-Juice Nov 04 '15 at 15:42
  • Check the link I sent you. Using nvarchar, is, in a sense, thinking into the future ;) – T. Sar Nov 04 '15 at 15:42

1 Answers1

1

Sure, in your OnModelCreating method, use this:

modelBuilder.Properties<string>().Configure(c => c.HasColumnType("varchar"));

In case you need to still have some string columns be NVARCHAR, you can just specify that on those specific properties after you use this command. According to Microsoft, FluentAPI operates in a "last wins" manner. So, you can do whatever you want to any property or group of properties, and if you make another change to the same property later, the one specified later will be the final result.

DrewJordan
  • 5,266
  • 1
  • 25
  • 39
  • This will work, but do you know if there is any other way to do it in case a table has both varchars and nvarchars? – Bert Wagner Nov 04 '15 at 16:27