>
> 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?
You are using Linq :) You could directly use Linq To XML to do that. i.e.:
XDocument asXmlDocument =
new XDocument(
new XDeclaration("1.0", "utf-8", ""),
new XElement("Parcels",
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 XElement("Parcel",
new XAttribute("Parcels_Id", p.Parcels_Id),
new XAttribute("Goods",g.Description),
new XAttribute("Inventory",pt.Description),
new XAttribute("RSReference",p.RSReference),
new XAttribute("Transaction_Nr",h.TransactionHeaders_Id),
new XAttribute("Transaction_Type",tt.TransactionTypes_Id),
new XAttribute("Date",h.TransactionDate),
new XAttribute("Weight",t.Weight),
new XAttribute("Amount",t.Amount)
)
)
);
using (XmlWriter xw = XmlWriter.Create(@"c:\docs\q.xml"))
{
asXmlDocument.Save(xw);
}
PS: Your Linq is questionable. A good database with relations setup have navigation properties and would not need all those joins. In Linq join is seldom needed. i.e. (using Northwind as a sample):
var orders = from o in db.Orders
select new
{
OrderId = o.OrderID,
Customer = o.Customer.CompanyName,
SalesMan = o.Employee.FirstName + " " + o.Employee.LastName,
OrderTotal = o.OrderDetails.Sum(od => od.UnitPrice * od.Quantity)
};