Question

Look at the below code

private static List<ExpandoObject> GetDBDetails()
        {
            var directoryPath = Environment.CurrentDirectory.Replace("\\bin\\Debug", "\\DataSource");
            var filePath = Path.Combine(directoryPath, "DBDetail.xml");
            try
            {
                //Load xml
                XDocument xdoc = XDocument.Load(filePath);
                if (xdoc == null) return null;


                List<ExpandoObject> dbDetails = (from dbDetail in xdoc.Descendants("database")
                                       select new ExpandoObject
                                            {
                                                DBDetailId = Convert.ToInt32(dbDetail.Attribute("dbDetailId").Value),
                                                DBServerId = Convert.ToInt32(dbDetail.Attribute("dbServerID").Value)
                                                                                                });
               return dbDetails;
            }
            catch (Exception ex)
            {
                McAfee.EnterpriseLibrary.Logging.LogUtil.LogEntry(ex, System.Diagnostics.TraceEventType.Critical);
                return null;
            }
        }

I am receiving the error

System.Dynamic.ExpandoObject' does not contain a definition for 'DBDetailId' System.Dynamic.ExpandoObject' does not contain a definition for 'DBServerId'

How to rectify this?

Was it helpful?

Solution

You need to cast the ExpandoObject to dynamic:

 xdoc.Descendants("database")
            .Select(dbDetail =>
                        {
                            dynamic expandoObj = new ExpandoObject();
                            expandoObj.DBDetailId = Convert.ToInt32(dbDetail.Attribute("dbDetailId").Value);
                            expandoObj.DBServerId = Convert.ToInt32(dbDetail.Attribute("dbServerID").Value);
                            return (ExpandoObject) expandoObj;
                        })
            .ToList();

Also you can cast ExpandoObject to IDictionary<string, object>:

var x = new ExpandoObject() as IDictionary<string, object>;
x.Add("DBDetailId", Convert.ToInt32(dbDetail.Attribute("dbDetailId").Value));
x.Add("DBServerId", Convert.ToInt32(dbDetail.Attribute("dbServerID").Value));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top