user3056117
user3056117

Reputation: 13

How to dynamically search property with value in TEntity?

I have an entity of type TEntity and I want to search dynamic property with given value.

public virtual TEntity Get(string code)
{
    var type = typeof(TEntity);
    if (!type.GetProperties().Any(x => x.Name == Constants.Columns.CODE))
    {
        throw new InvalidOperationException($"{typeof(TEntity)} doesn't have any {Constants.Columns.CODE} property.");
    }

    return _entities.FirstOrDefault(x => type.GetProperty(Constants.Columns.CODE).GetValue(x).ToString() == code);
}

Upvotes: 0

Views: 490

Answers (2)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 88996

You can use the Shadow Property-style access syntax for any property. So simply add the following method to your DbContext:

public IQueryable<TEntity> FilterBy<TEntity, TValue>(string propertyName, TValue value) where TEntity : class
{
    return Set<TEntity>().Where(e => EF.Property<TValue>(e,propertyName).Equals(value));
}

Upvotes: 2

Gonzalo Martinez
Gonzalo Martinez

Reputation: 95

To get started, I think that the next code could help you:

// Person Class
 public class Person
    {
        public string Name { get; set; }
        public uint Age { get; set; }
    }
  private static Person GetEntity(List<Person> personList, string propertyName, string propertyValue)
        {
            Person person = personList.FirstOrDefault(x =>
            {
                PropertyInfo a = x.GetType().GetProperties()
                                            .Where(y => y.Name == propertyName)
                                            .FirstOrDefault();     

                return a.GetValue(x)?.ToString() == propertyValue;
            });

            return person;
        }
  static void Main(string[] args)
        {
            List<Person> personList = new List<Person>()
            {
                new Person()
                {
                    Age=10,
                    Name="aa"
                },
                new Person()
                {
                    Age=20,
                    Name="bb"
                }
            };               

            //Get the first person of the list:
            Person p = GetEntity(personList, "Name", "aa");

            //....

I dont have seen completly your code, but i think that applying this change at the last code line, could be work:

 var _entity = _entities.FirstOrDefault(x =>
            {
                var properties = x.GetType().GetProperties()
                                            .Where(y => y.Name == Constants.Columns.CODE)
                                            .FirstOrDefault();     

                return properties.GetValue(x)?.ToString() == code;
            });

return _entity;

Upvotes: 1

Related Questions