C #: change DataType data type for Entity Framework

I am trying to transform a project that is currently using a custom DAO structure to use the Entity Framework. The system is quite large, so changes to the database (SQL Azure DB, if that matters) alone are not particularly possible, and should be avoided if possible.

The problem is the ID column. Unfortunately, when the system was created, there are several tables with the bigint type, and some of them have int , but the models themselves are all from the base class, which has a long for the identifier. The previous structure was able to handle this situation, but I could not find a way to do this using the framework entity.

Below is the most trivial example I can come up with:

 public class Context : DbContext { public IDbSet<Foo> Foos {get;set;} public IDbSet<Bar> Bars {get;set;} } public abstract class BaseClass { public long ID; } public class Foo : BaseClass { ... } public class Bar : BaseClass { ... } SQL Table: Foo +-------------+ | id : bigint | | ... | +-------------+ SQL Table : Bar +-------------+ | id : int | | ... | +-------------+ 

When I try to load the Bar model, I get this error:

 The 'ID' property on 'BaseClass' could not be set to a 'Int32' value. You must set this property to a non-null value of type 'Int64'. 

I would like to find a way to tell the system that there are ints in the bar, while Foo has longs. I tried to override OnModelCreating in context and define HasColumnType for Bar . This gave me a new error:

 Schema specified is not valid. Errors: (105,12) : error 2019: Member Mapping specified is not valid. The type 'Edm.Int64[Nullable=False,DefaultValue=]' of member 'ID' in type 'Bar' is not compatible with 'SqlServer.int[Nullable=False,DefaultValue=,StoreGeneratedPattern=Identity]' of member 'ID' in type 'CodeFirstDatabaseSchema.Bar'. 

It seems to me that if I can only change the expected data type for the ID from BaseClass to int before sending the request to the server, then I should be able to up-convert to long after receiving the response. Ideally, I would like to do this based on a class.

Can someone point me in the right direction?

+7
source share
1 answer

While you can implicitly use bigint for int in SQL Server , it seems that the EDM types of EDM (which are actually what you are dealing with) do not allow implicit conversion from a 64-bit integer type to a 32-bit integer type of.

This is probably not without reason, because you can easily overflow and have values ​​that don't match int fields.

However, you should have two base classes: one for the identifier int and one for the identifier long . It is not very, but it provides the logic that you definitely want; you cannot store values ​​that are larger than what can fit in an int in the database, so why would you want to do this at the code level? The Entity structure does the right thing here, not allowing you to apply this transformation.

+4
source

All Articles