Use int Id for a bigint column in EF6

c# entity-framework entity-framework-6


A data layer is being constructed using Entity Framework 6 on top of a legacy SQL Server database with type Id columns.bigint We wish to utilizeint instead of for our Id column typeslong , and we're certain that the tables will never increase in size above what anint .

But we're encountering the following error:

The specified cast from a materialized 'System.Int64' type to the 'System.Int32' type is not valid.

How can we accomplish our goals without changing the database column type?

8/28/2015 8:45:28 AM

Accepted Answer

The DataType of the column in your database should be able to be specified.OnModelCreating approach for every model impacted):

    .Property(p => p.Id)   

If each Id in each model is associated with a,bigint , you may then employ a unique convention:

   .Where(p => p.Name == "Id")
   .Configure(c => c.HasColumnType("bigint"));

Another strategy would be to give all Models with a base class that is abstract.bigintId (And in this example, data annotation is used in place of the fluent API:

public abstract class BaseModel
   public int Id { get; set; }


configuring a column's data type

individual conventions

8/28/2015 3:30:58 PM

Popular Answer

What about the following?

class DbEntity
    private Int64 Id { get; set; }

    public int SmallerId { 
        get { return Convert.ToInt32(Id); }

This approach is applicable to many kinds of mappings, such as Yes/No to true/false (see this inquiry).

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow