0

I know that this title may be asked already, however these solutions recommend to use ExpandoObject which did not help me.

I have read:

  1. access properties from anonymous types
  2. dynamic does not contain a definition for a property

I am using Entity Framework 6 and I have an anonymous object (which depends on some different tables) and I have to use dynamic object.

How can I retrieve fields from a dynamic object?

public void main()
{
    dynamic caller = new ExpandoObject();
    caller = CustomerServices.GetByCallerId(callerId);
    DateTime CallDateTime = caller.CallDateTime; // Cause the Error
    int CallerId = caller.CallerId; // Cause the Error
}

public dynamic GetByCallerId(string callerId)
{
    dynamic customerCall = new ExpandoObject();        
    using (MehrpouyanEntities dbContext = new MehrpouyanEntities())
    {
        customerCall = dbContext.Customers.Where(r => r.LandlinePhone1 == callerId || r.LandlinePhone2 == callerId || r.MobilePhone1 == callerId || r.MobilePhone2 == callerId).Select(r=>new {Caller = "myCaller", CallerId = r.Id, Name = r.Name, PhoneNumber = callerId, Address = r.Address, CallDateTime = DateTime.Now}).FirstOrDefault();
        return customerCall;
    }
}
Hosein Aqajani
  • 1,553
  • 4
  • 26
  • 46
  • 1
    Why are you using anything dynamic at all? Your function should just return a `Customer` object. – DavidG Sep 29 '17 at 15:53
  • I need it because the caller may be a `Customer` or `Operator` or `User` or `Worker` so I want to have a dynamic object to get it flexibility. Moreover, if you notice to my Select, it cause to create a dynamic object and the function could not return a Customer any more – Hosein Aqajani Sep 29 '17 at 16:01
  • 1
    ...but your method only looks at the Customers table? – Equalsk Sep 29 '17 at 16:05
  • Firstly I told that the `Select` after `Where` change the output, Secondly I did not bring all of my code here. – Hosein Aqajani Sep 29 '17 at 16:06
  • 1
    `dynamic caller = new ExpandoObject();` is a waste as you assign a different object to `caller` on the next line. – crashmstr Sep 29 '17 at 19:17
  • Either *all* of your object types have `CallDateTime` and `CallerId` or you need to *test* for that. Also, if *all* have those, then use inheritance or an interface to return objects that can be used more easily. – crashmstr Sep 29 '17 at 19:19
  • Dear @crashmstr , I have to use dynamic object due to handle an anonymous type, so I neither could solve this problem via inheritance nor with interface – Hosein Aqajani Sep 29 '17 at 19:27
  • 1
    Sure does look like the kind of situation NOT to use dynamic types. There is not enough code there to say that with 100% certainty, but if you can't use interfaces or inheritance because that method could return so many significantly different things, maybe your class does too many things. I'd suggest you look at your solution and see if you could improve on the S & I of SOLID. – Tipx Sep 29 '17 at 19:39

0 Answers0