skip to Main Content

I would like to get the value of @@SERVERNAME. The following code works:

[Keyless]
public class EntityString
{
    public String Value { get; set; } = String.Empty;
};

// inside MyDbContext.OnModelCreating
modelBuilder.Entity<EntityString>();

// inside MyDbContext
public IQueryable<EntityString> QueryServerName()
     => Set<EntityString>().FromSqlRaw("SELECT @@SERVERNAME as Value");

// At usage site
ServerName = (await WHContext.QueryServerName().FirstAsync()).Value

However it seems overly complex for the simple task. Is there an easier way to execute a SELECT query that is expected to return a single string value?

Using String instead of EntityString gave a runtime error that an entity class was required .

2

Answers


  1. Chosen as BEST ANSWER

    The following change worked:

    // In MyDbContext class
    public IQueryable<EntityString> QueryServerName()
         => Database.SqlQueryRaw<String>("SELECT @@SERVERNAME as Value").AsQueryable();
    
    // usage 
    ServerName = await MyContext.QueryServerName().SingleAsync();
    

    Using SqlQuery gave an error that string could not be converted to FormattableString.

    Omitting the as Value from the query string gave a runtime error "No column name was specified for column 1 of 't'. Invalid column name 'Value'."


  2. You can do something like this

    // Inside MyDbContext.OnModelCreating
    modelBuilder.Entity<string>().HasNoKey().ToView("ServerName");
    
    // Inside MyDbContext
    public async Task<string> GetServerNameAsync()
    {
        return await Set<string>().FromSqlRaw("SELECT @@SERVERNAME as 
           Value").FirstOrDefaultAsync() ?? string.Empty;
    }
    
    // At usage site
    ServerName = await WHContext.GetServerNameAsync();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search