2

I have this EF Core query on a SQL Server database to get the database collation (code from Copilot):

var collation = dbContext.Database.SqlQuery<string>($"SELECT collation_name FROM sys.databases WHERE name = DB_NAME()").FirstOrDefault();

I get this response:

SqlQuery result : Microsoft.Data.SqlClient.SqlException: 'Nom de colonne non valide : 'Value'.'

Translation (I think):

SqlQuery result : Microsoft.Data.SqlClient.SqlException: 'Invalid column name : 'Value'.'

I'm using

  • Microsoft.EntityFrameworkCore (9.0.7)
  • Microsoft SQL Server 2019 (RTM-CU32-GDR) (KB5058722) - 15.0.4435.7 (X64)

Why does this happen?

1 Answer 1

6

SqlQuery expects the single column to be called Value.

Also database_id is the primary key, you should use that.

var collation = dbContext.Database.SqlQuery<string>(
   $"""
       SELECT collation_name AS Value
       FROM sys.databases
       WHERE database_id = DB_ID()
    """).FirstOrDefault();
Sign up to request clarification or add additional context in comments.

1 Comment

It works with "name = DB_NAME()" because it returns a single row but I agree it is a better practice to use the primary key instead and I will change my code to follow yours!

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.