Entity Framework. C# To SQL Type Translation

When you declare a variable in Entity Framework model, migration translates the C# type to SQL Server type. Here is a table describing how each C# type is implemented in SQL.

C# primitive type C# type in System namespace SQL Server type
byte Byte tinyint
short Int16 smallint
int Int32 int
long Int64 bigint
 float Single real
double Double float
decimal Decimal decimal(18,2)
bool Boolean bit
DateTime datetime
char Char
string String nvarchar(max) null

Just two interesting things:

  1. char type is not translated to any SQL type;
  2. string type is the only type that will be nullable, the others are not.

And some tips:

  1. to make a field NULL, for example int, you should use a nullable type int? instead;
  2. to make a string field NOT NULL, place a [Required] attribute before declaration in EF model;
  3. if your string field won’t have an infinite length, you can (and I recommend to) place a [StringLength(n)] attribute where n can be up to 4000.

[UPDATE 2016-11-17]
Unsigned integer types and sbyte are not translated too. See here Not All .NET Types Can Be Used In Entity Framework

Leave a Reply

Your email address will not be published. Required fields are marked *