0

I'm trying to get values from database it is working perfect with raw sql query but not working with linq. I'm sharing my code please guide me

LINQ:

using (var db = new SContext())
{
    var abc = db.Locales
                .Where(c => c.Culture == cultureName && c.Key == key)
                .Select(a => a.Value);

   return abc.ToString();
}

SQL RAW (Working Perfect)

using (var conn = new SqlConnection(_connectionString))
{
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "SELECT [Value] FROM [Spenotics].[dbo].[Locale] WHERE [Key] = @key AND [Culture] = @culture";
        cmd.Parameters.AddWithValue("key", key);
        cmd.Parameters.AddWithValue("culture", cultureName);
        conn.Open();
        var value = cmd.ExecuteScalar();
        return (string)value;
     }
}

I want to convert sql query in to linq but it is giving error "object reference not set to an instance of an object"

Ocelot20
  • 9,720
  • 9
  • 49
  • 96
DevWithSigns
  • 598
  • 12
  • 31

1 Answers1

0

Whenever you needs only one element from the query then it would be ideal to use one of the bellow

. First() - throws if empty/not found, does not throw if duplicate

. FirstOrDefault() - returns default if empty/not found, does not throw if duplicate

. Single() - throws if empty/not found, throws if duplicate exists

. SingleOrDefault() - returns default if empty/not found, throws if duplicate exists

var abc = db.Locales
                .Where(c => c.Culture == cultureName && c.Key == key)
                .Select(a => a.Value).FirstOrDefault();

In SQL raw also it would be ideal to use TOP 1

SELECT TOP 1 [Value] FROM [Spenotics].[dbo].[Locale] WHERE [Key] = @key AND [Culture] = @culture