Home > Software engineering >  Get EF Core value by property name?
Get EF Core value by property name?

Time:10-24

From this SO answer I'm trying to build a text replace function.

The problem is that it can't do multi level. Or at least I don't know how.

If I have this query:

var foo = await _dbContext.Foos.Include(x => x.Bar).AsNoTracking().FirstOrDefaultAsync(x => x.Id == someId);

I can do:

var fooName = GetPropertyValue(foo, "Name");

But I can't do:

var barName = GetPropertyValue(foo, "Bar.Name");

Is that possible?

public class Foo
{
    public string Name {get;set;}
    public Guid BarId {get;set;}
    public Bar Bar {get;set;}
}

public class Bar
{
    public string Name {get;set;}
}

CodePudding user response:

You simply need to the function twice, once to get the Bar object and once again to get the Name property of Bar:

var bar = GetPropertyValue(foo, "Bar");
var barName = GetPropertyValue(bar , "Name");

This should give the desired result.

CodePudding user response:

You need a recursive version of the aforementioned method. You may try something like below:

        public static string? GetPropertyValue(object source, string propertyName)
        {
            try
            {
                return GetInnerProp(source, propertyName) as string;
            }
            catch { return null; }
        }

        private static object GetInnerProp(object source, string propertyName)
        {
            if (propertyName.Contains('.'))
            {
                var propertyNames = propertyName.Split(".");
                var firstProp = propertyNames.First();
                var newSource = source.GetType().GetProperty(firstProp).GetValue(source, null);
                var rest = string.Join(".", propertyNames.Skip(1));

                return GetInnerProp(newSource, rest);
            }

            return source.GetType().GetProperty(propertyName).GetValue(source, null);
         
        }

It basically split the property name and recursively walks from left to right to access the right property. You also will need an inner method that returns an object as the nested object will have a type other than string.

Fiddle

  • Related