I have a table with many fields, I am using EF Core for access,
it is possible to return only the fields that I will actually use?
Assuming you have the following entity:
public class MinhaEntidade
{
public int Propiedade1 { get; set; }
public int Propiedade2 { get; set; }
public int Propiedade3 { get; set; }
public int Propiedade4 { get; set; }
public int Propiedade5 { get; set; }
public int Propiedade6 { get; set; }
public int Propiedade7 { get; set; }
public int Propiedade8 { get; set; }
public int Propiedade9 { get; set; }
}
You can do something like this example:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Random rnd = new Random();
var entidade = new List<MinhaEntidade>();
//Preencher alguns valores aleatórios
for(int i = 0; i < 5; i++)
{
entidade.Add(
new MinhaEntidade{
Propiedade1 = rnd.Next(),
Propiedade2 = rnd.Next(),
Propiedade3 = rnd.Next(),
Propiedade4 = rnd.Next(),
Propiedade5 = rnd.Next(),
Propiedade6 = rnd.Next(),
Propiedade7 = rnd.Next(),
Propiedade8 = rnd.Next(),
Propiedade9 = rnd.Next()
}
);
}
//Seleciona apenas 3 itens da MinhaEntidade para um objeto anonimo
var teste = entidade.Select(q => new
{
propX = q.Propiedade1,
propY = q.Propiedade4,
propZ = q.Propiedade9
}).ToList();
//Imprime os itens selecionados:
foreach(var item in teste)
{
Console.WriteLine(string.Format("{0}, {1}, {2}", item.propX, item.propY, item.propZ));
}
}
}
See working on . NET Fiddle.
Would dapper be an option? with Dapper I can only return a few
table columns and map to my domain class ?
Yes, with Dapper
it is also possible, you can return a dynamic
with only the items you want:
var resultado = conexaoBD.Query("Select coluna1, coluna3, coluna7 from MinhaTabela");
//Retorna uma lista de objetos dinâmicos eliminando a necessidade de definir objeto.
Console.WriteLine("{0} - {1} - {2} ", "Item 1", "Item 2", "Item 3");
I think this is the idea, but in fact the data is not moving on the network? It seems that everything came from the bank, but only some fields were populated. Or in this case only properties 1.4 and 9 are returned from the database to the application?
– Alexandre Previatti
The doubt is due to the fact that there are fields with a large volume of text (news), but in the listing only the title and not the text (news body). If I list 100 news on a page (just ex.) could bring the bank to the application a much smaller volume if I manage to traffic only ID and Title...
– Alexandre Previatti
@Alexandrepreviatti, in the example, in the section that looks like this ." Select(q => new..." the select brings from the database only the fields that you specified even. What you cannot do is select from your 'complete object' and then select the fields you want. You can see the select generated by EF to confirm this, but I don’t think it’s scope of this answer.
– George Wurthmann