Use Select method allows us to get the properties of the object and returns a new list of elements of a database using Entity Framework Core.
using EntityFrameworkCore_ConsoleApp.Models;
namespace EntityFrameworkCore_ConsoleApp
{
public class Program
{
static void Main(string[] args)
{
using (var databaseContext = new DatabaseContext())
{
var products = databaseContext.Products.Select(product => new
{
Id = product.Id,
Name = product.Name,
Price = product.Price
}).ToList();
products.ForEach(product =>
{
Console.WriteLine("Id: " + product.Id);
Console.WriteLine("Name: " + product.Name);
Console.WriteLine("Price: " + product.Price);
Console.WriteLine("---------------------");
});
}
}
}
}
Output
Id: 9
Name: Tivi 1
Price: 10
---------------------
Id: 10
Name: Tivi 2
Price: 5
---------------------
Id: 11
Name: Tivi 3
Price: 20
---------------------
Id: 12
Name: Laptop 1
Price: 15
---------------------
Id: 13
Name: Laptop 2
Price: 4
---------------------
Id: 14
Name: Computer 1
Price: 17
---------------------
Id: 15
Name: Computer 2
Price: 43
---------------------
Id: 16
Name: Computer 3
Price: 19
---------------------
You can use combination of Select method and Where method as below:
using EntityFrameworkCore_ConsoleApp.Models;
namespace EntityFrameworkCore_ConsoleApp
{
public class Program
{
static void Main(string[] args)
{
using (var databaseContext = new DatabaseContext())
{
var products = databaseContext.Products.Where(product => product.Status == true).Select(product => new
{
Id = product.Id,
Name = product.Name,
Price = product.Price
}).ToList();
products.ForEach(product =>
{
Console.WriteLine("Id: " + product.Id);
Console.WriteLine("Name: " + product.Name);
Console.WriteLine("Price: " + product.Price);
Console.WriteLine("---------------------");
});
}
}
}
}
Output
Id: 9
Name: Tivi 1
Price: 10
---------------------
Id: 12
Name: Laptop 1
Price: 15
---------------------
Id: 14
Name: Computer 1
Price: 17
---------------------
Id: 16
Name: Computer 3
Price: 19
---------------------