问题
I want to use Massive for data access with WCF Web Api and return either dynamic or ExpandoObject / IEnumerable<ExpandoObject> from my web api.
I have this basically working using a JsonNetMediaTypeFormatter which uses Json.NET's ExpandoObject serialization, but everything gets returned as a Key-Value pairs in the Json such as:
[
{
"Key":"ID",
"Value":"1000"
},
{
"Key":"FirstName",
"Value":"John"
},
{
"Key":"LastName",
"Value":"Smith"
}
]
But, what I want is:
[
{
"ID":"1000",
"FirstName":"John",
"LastName":"Smith",
}
]
As if I were using a concrete type like:
public class Customer
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Any ideas on how to get the dynamic/ExpandoObject formatted like a concrete object when returned from WCF Web Api?
回答1:
Some elaboration on Custom Media Type formatters for Web WCF:
http://geekswithblogs.net/michelotti/archive/2011/06/06/understanding-custom-wcf-web-api-media-type-processors-on-both.aspx
I'm guessing he might be using json.net or another library for dynamic object serialisation
http://blogs.clariusconsulting.net/kzu/using-json-net-for-text-and-binary-json-payloads-with-wcf-webapi/
Web WCF
http://wcf.codeplex.com/wikipage?title=WCF%20HTTP
回答2:
I think you are taking Expando Query and passing to WCF. Just try to do iteration or just give ToList to your collection. That will convert ExpandoQuery to Expando Object Collection. And if you are POCO to map, as Customer is there like in your question. Give a Select with your POCO objects.
Like if your query is
Dynamic CustomerTable = DynamicObject("ConnectionString","TableName","PrimeryKey");
CustomerTable.All() //This will be ExpandoQuery
CustomerTable.All().Select(c=> new Customer () {FistName = c.FirstName, LastName = c.LastName}); // This will give collection of customer object. Just pass this as DTO to your WCF service.
I hope this will help you. Let me know if anything further is there.
来源:https://stackoverflow.com/questions/7970083/massive-with-wcf-web-api-to-return-dynamic-types-expandos