0

I need to retrieve a dyanmic object list from entity frmework to generate dynamic report. Normally, In EF: db.People.ToList() will return pepole list.

What I need here is a dynamic way.

i.e, if a user passes 'People' to the following method, it should return pepole list. If 'Address', then address object list will be returned.

public IEnumerable<object> GetReportModelList(string viewName)
    {          

        var reportList = _baseEntities.Database.SqlQuery<dynamic>(string.Format("Select * from [dbo].{0}", viewName);

        foreach (var report in reportList)
        {
            var test = report.GetType().GetProperty("DimensionCode");
            var test2 = report.GetType().GetProperties();
            //foreach(PropertyInfo prop in report.GetType().GetProperties())
            //{
            //    String value = prop.GetValue(report, null);
            //}
        }

        return null;
    }

As above codes, I'm struggling to get values of properties from dynamic object. Any advice, please?

1 Answer 1

3

What is db? If it derives from DbContext, you can make your method generic like this:

public IEnumerable<T> GetReports<T>() where T : class
{
   return db.Set<T>().AsEnumerable();
}

You can call it like this:

var personList = GetReports<People>();

or:

var addressList = GetReports<Address>();
Sign up to request clarification or add additional context in comments.

2 Comments

Do you have or are you able to create DbSet objects within you DbContext class for each of the tables you need to query? What error messages are you getting? I don't think you can use dynamic in this context because EF will treat the type as an object when it tries to evaluate it at runtime.
It is returning null values now. I thought List<object> can return from DAL layer. Then, I will get property values of each objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.