2

There is an int ID column in a MS SQL database table, but the entity class contains a long ID field, and I get the following message in the context:

"An exception occured while reading a database value. The expected type was 'System.Int64' but the actual value was of type 'System.Int32'."

I've already tried to set the column type:

modelBuilder.Entity<XXXEntity>()
            .Property(b => b.Id)
            .HasColumnName("XXXId")
            .HasColumnType("int");

but that does not work. What's the right solution?

I cannot change neither the entity class nor the db table.

4
  • change the long id field to int? Commented May 17, 2017 at 8:43
  • I cannot change it Commented May 17, 2017 at 8:45
  • force it to be int by using Convert.ToInt32(myLongIdField). But there is valid reason why the program doesn't allow you to insert long into int type column. use this only if you are very sure that your "long" data will not be too big. Commented May 17, 2017 at 8:49
  • I do not want to insert data, I just want to read it Commented May 17, 2017 at 8:52

2 Answers 2

2

You should map Int64 into bigint on SQL server:

 modelBuilder.Entity<XXXEntity>()
            .Property(b => b.Id)
            .HasColumnName("XXXId")
            .HasColumnType("bigint");

UPDATE: Since your SQL column data type is int, you should change your Id datatype inside XXXEntity class to Int32

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks, but the same result.
@Aaaaaaaa what is the actual type of XXXId column on SQL Server?
int, as I wrote
@Aaaaaaaa then you should have two different Id properties. One for legacy db (e.g. LegacyId which corresponds to datatype inside legacy db) and one for new db (e.g. Id which corresponds to datatype of new db)
If there is no other solution, than I schould have two IDs, yes. Thanks!
|
0

Not tested. But can try?

public long id { get { return id; } set { id.GetType() == typeof(Int64) ? id : Convert.ToInt64(id); }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.