Use int Id for a bigint column in EF6

c# entity-framework entity-framework-6

Question

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?

1
5
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):

modelBuilder.Entity<Department>()   
    .Property(p => p.Id)   
    .HasColumnType("bigint");

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

modelBuilder.Properties<int>()
   .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
{
   [Column(TypeName="bigint")]
   public int Id { get; set; }
}

References:

configuring a column's data type

individual conventions

12
8/28/2015 3:30:58 PM

Popular Answer

What about the following?

class DbEntity
{
    [Key]
    private Int64 Id { get; set; }

    [NotMapped]
    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





Related

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