Viv, Naomi, thank you very much for your suggestion. But that somehow defeats the very concept of anonymous types no? Using a json library, I was perfectly able to serialize an anonymous type, I wonder why that is not implemented for xml which conceptually is very similar.
>>
>> public static void GetTransactions()
>> {
>> using (var context = new PICSEntities(Config.model.SqlServer))
>> {
>> var q = from p in context.Parcels
>> join pt in context.ParcelInventoryTypes on p.ParcelInventoryTypes_Id equals pt.ParcelInventoryTypes_Id
>> join t in context.TransactionDetails on p.Parcels_Id equals t.Parcels_Id
>> join h in context.TransactionHeaders on t.TransactionHeaders_Id equals h.TransactionHeaders_Id
>> join g in context.GoodsTypes on p.GoodsTypes_Id equals g.GoodsTypes_Id
>> join tt in context.TransactionTypes on h.TransactionTypes_Id equals tt.TransactionTypes_Id
>> select new
>> {
>> Parcels_Id = p.Parcels_Id,
>> Goods = g.Description,
>> Inventory = pt.Description,
>> RSReference = p.RSReference,
>> Transaction_Nr = h.TransactionHeaders_Id,
>> Transaction_Type = tt.TransactionTypes_Id,
>> Date = h.TransactionDate,
>> Weight = t.Weight,
>> Amount = t.Amount
>> };
>> // Json.serialize(q, @"c:\docs\q.json");
>> Monitor.Console($"Extracted {q.Count()} records.");
>> using (var fs = new System.IO.FileStream(@"c:\docs\q.xml", System.IO.FileMode.Create))
>> {
>> System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(q.GetType());
>> x.Serialize(fs, q);
>> }
>> }
>> }
>>
>>This breaks here :
>>
>> System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(q.GetType());
>>
>>Cannot serialize anonymous types.
>>Is there a way around this?
>
>As Naomi says you will need to create a class to hold the results and also convert the result to a list for serialization. e.g:
public class Thing
> {
> public int Parcels_Id { get; set; }
> public string Goods { get; set; }
> // etc
> }
then:
select new Thing{Parcels_Id = Parcels_Id.......}
>//and:
> using (var fs = new System.IO.FileStream(@"c:\docs\q.xml", System.IO.FileMode.Create))
> {
> System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Thing[]),new XmlRootAttribute("MyThings"));
> x.Serialize(fs, q.ToArray());
> }
If things have the tendency to go your way, do not worry. It won't last. Jules Renard.