NicTamHK NicTamHK - 4 years ago 210
SQL Question

Returning a String from a SQL query in MVC Entity Framework 6 Controller

I want to execute a basic SQL query (e.g. "SELECT string FROM table WHERE criteria = TRUE) on MVC Entity Framework 6. The returned type is to be a string. I have tried many possible things but they return the SQL query string or something completely irrelevant, such as:

SELECT [Extent1].[Fname] AS [Fname]
FROM [dbo].[Developer] AS [Extent1]
WHERE ([Extent1].[Login] = @p__linq__0)
OR (([Extent1].[Login] IS NULL) AND (@p__linq__0 IS NULL))

I have the following in my controller:

var data = db.Developers.Where(y => y.Login.Equals(username)).ToList();

This is my

public partial class Developer
public int PersonID { get; set; }
public string Fname
get { return Fname.ToString(); }
set { Fname = value;}
public string Lname { get; set; }
public string Developer1 { get; set; }
public string Login { get; set; }
public Nullable<bool> IsManager { get; set; }
public Nullable<bool> IsPF { get; set; }
public Nullable<bool> IsLW { get; set; }
public string Prov { get; set; }

I would like to get the string that this query returns.

Somehow this works when this is made to a List and passed to the View model, where it is displayed using

Is there a way to execute my SQL command in my controller and get a string value in return?

Answer Source

FirstOrDefault() to return the first element, in this case there is only one.

You should include a validation if username doesnt exist.

Developer myDeveloper = db.Developers
                         .Where(y => y.Login.Equals(username))

return myDeveloper.Lname;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download