3

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?

bytecode77
  • 14,163
  • 30
  • 110
  • 141
priyanka.sarkar
  • 25,766
  • 43
  • 127
  • 173
  • Another alternative http://stackoverflow.com/questions/13704752/deserialize-xml-to-object-using-dynamic – I4V May 08 '13 at 10:57
  • Any reason you are using an `ExpandoObject` and not creating a new class like 'DbDetails`, for this specific purpose? The Intellisense won't work outside of this method and passing around `dynamic` isn't a good idea either. – Dominic Zukiewicz May 08 '13 at 11:28
  • Because the object type is not known to me and i cannot create concrete classes as it is a constraint (: – priyanka.sarkar May 08 '13 at 11:55

1 Answers1

4

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));
Vyacheslav Volkov
  • 4,592
  • 1
  • 20
  • 20