Return the Dbquery property name using Generics

Asked

Viewed 44 times

1

How do I get the name of the property DbQuery using Generics?

I have the property:

public DbQuery<Pessoa> ConsultarPessoas { get; set; }

And in my repository:

DataContext.Query<T>().FromSql("ConsultarPessoas");

So far so good. Now I need to take the name of the property via Generics and set in place of ConsultarPessoas.

It’s been a while since I’ve been researching.

?DataContext.Query<T>()
?DataContext.Query<T>().GetType()
?nameof(?DataContext.Query<T>())
  • And why do you need this? Almost every time I see this kind of need there’s an impression that you’re using something wrong and you don’t really need it, you can solve it in a better way.

  • @Maniero I usually take dbset in the constructor: dbset = Datacontext.Set<T>() and use it when requested: dbset. Find(id). Since I never bothered to know the name of the property. Now I intend to run a trial with fromSql() and I have to pass it in the parameter.

2 answers

1


The solution that met was:

var result = DataContext.GetType().GetProperties()
.Where(x => x.PropertyType.FullName == 
dbQuery.GetType().BaseType.FullName).FirstOrDefault().Name

Thank you all.

0

Ronaldo,

If you are using within a generic class, the name you have from:

typeof(T).Name;

In that context something like:

DataContext.Query<T>().FromSql(typeof(T).Name);

I’m not sure I understand your environment but I hope I’ve helped.

  • Hello @Thiago-Araújo in query returns entity: ? typeof(T). Name "Person" ? Datacontext.Query<T>(). FromSql(typeof(T).Name)&#xA;{Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable<Pessoa>}&#xA; ElementType: {Name = "Pessoa" FullName = "System.Pessoa"}&#xA; Expression: {value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[System.Pessoa]). Fromsqlonqueryable("Person", value(System.Object[]))} Provider: {Microsoft.EntityFrameworkCore.Query.Internal.Entityqueryprovider} Results View: Expanding the Results View will enumerate the Ienumerable

Browser other questions tagged

You are not signed in. Login or sign up in order to post.