I have Manufacturer
entity as below:
class Manufacturer
{
[Key]
public int Id { get; set; }
[DisplayName("Manufacturer Code")]
public int Code { get; set; }
[DisplayName("Manufacturer Name")]
public string Name { get; set; }
}
As you see every filed have DisplayName
data annotations. In Normal way I select the rows of Manufacturer table by below code:
dataGridView1.DataSource = DatabaseContext.Set<Manufacturer>()
.Select(m => new
{
Id = m.Id,
Code = m.Code,
Name = m.Name,
})
.ToList();
I want to find a way that Dynamically put DisplayName as alias in Linq query.
I think I must a Method that generate the query something like:
dataGridView1.DataSource = DatabaseContext.Set<Manufacturer>()
.Select(m => new
{
Id = m.Id,
[Manufacturer Code] = m.Code,
[Manufacturer Name] = m.Name,
})
.ToList();
I could get the all DisplayName
by below code:
public static Dictionary<string, string> GetEntityDisplayName(this Type type)
{
return TypeDescriptor.GetProperties(type)
.Cast<PropertyDescriptor>()
.ToDictionary(p => p.Name, p => p.DisplayName);
}
But dont know how do that. Is there any way to put DisplayName
as alias of Linq query dynamically?
Update:
As one of answer say when use .ToList
in get rows from an entity it return a list that project the model with DisplayNameAttribute
, But the new thing is When create Linq query that use 2 entity, to list project the row that you exactly say in query. For example:
class Manufacturer
{
[Key]
public int Id { get; set; }
[DisplayName("Manufacturer Code")]
public int Code { get; set; }
[DisplayName("Manufacturer Name")]
public string Name { get; set; }
}
And:
class Good
{
[Key]
[DisplayName("ID")]
public int Id { get; set; }
[DisplayName("Good Name")]
public string Name { get; set; }
public int? ManufacturerId { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
}
And The Query:
using (AppDbContext db = new AppDbContext())
{
var res2 = db.Goods.Select(m => new
{
Id = m.Id,
GoodsName = m.Name,
ManufacturerName = m.Manufacturer.Name,
}).ToList();
dataGridView1.DataSource = res2;
}
As you see in this case, because the query have 2 name field, must declare different alias for them and its not the equal to DisplayNameAttribute
in entity. Are anyone know a way to project the output list same as DisplayNameAttribute
defined in entity?