I'm trying to do a simple thing: to get the MAX of a column. Is quite simple, you know, just run SELECT MAX(column) FROM table;
The problem is when I try to do this in my .NET Core 2.1 project, using Entity Framework.
I have a function that should return the next value of a column.
private int getColumNextValue(string table, string column)
{
string query = $"SELECT MAX({column}) + 1 FROM {table};";
return base.context.Database.ExecuteSqlCommand(query);
}
The query is being generated correclty:
However, it's returning -1 instead of the real value.
But when I run the exact same query in Sql Server Management Studio, the result is correct:
What's going on?
MAX(ID) +1
can easily return duplicates if eg the latest row is deleted. That's why it's seldom used to generate IDs. UseIDENTITY
or a SEQUENCE instead. EF has no trouble working with IDENTITY values either. It doesn't have to know the IDs in advance to set up foreign keys. When a new root object and nested objects are added, EF will generate the appropriate statements to set all IDs according to the relations configured on the DbContext – Panagiotis Kanavos Mar 26 '19 at 15:34IDENTITY
, so I have to use the MAX+1 strategy... Sad but it's the reality. So, I need to execute an insert query into the legacy db through a secondary connection, that's why I need to run a query on the fly, without binding it to a model. – rom5jp Mar 26 '19 at 21:44