Is there a way that I can select specific columns?
Create a type that contains only the properties you wish to return (view model). Populate the new type like you're doing with the Tbl016 type (projection query).
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I'm using this method to return specific rows with specific columns from a SQL DB using EntityFramework Core
Even with the ".Select(x => new Tbl016" expression I still get every single column in the table. Is there a way that I can select specific columns?
Is there a way that I can select specific columns?
Create a type that contains only the properties you wish to return (view model). Populate the new type like you're doing with the Tbl016 type (projection query).
@Mohammad Radawan , you could use linq method select new
to return the specific columns.
I make a code example and you can refer to it. (Here I use list to replace the dbcontext.Agents)
class Program
{
static List<Student> context = new List<Student>();
static void Main(string[] args)
{
context.Add(new Student { UserName = "test1", Password = "123456", ID = 1001, Age = 21, Address = "home1" });
context.Add(new Student { UserName = "test2", Password = "123456", ID = 1002, Age = 21, Address = "home1" });
context.Add(new Student { UserName = "test3", Password = "123456", ID = 1003, Age = 21, Address = "home1" });
context.Add(new Student { UserName = "test4", Password = "123456", ID = 1004, Age = 21, Address = "home1" });
var result = checkifusername("test1", "123456");
}
public static object checkifusername(string username,string password)
{
return (from stu in context
where (stu.UserName == username && stu.Password == password)
select new
{
LoginUserName = stu.UserName,
LoginPassword = stu.Password,
Id=stu.ID
}).FirstOrDefault();
}
}
public class Student
{
public int ID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
Result:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.