I'm not sure if I'm going about this right. I'm try to select just a few items that I get back from the LINQ query. Eventually I'll want to pull back most of the information, but some of the fields are FK ID's so I'll have to get their name values from other tables.
The problem I'm having right now is the list conversion from Anonymous to Bills. How do I get around this?
public class BillDO
{
/// <summary>
/// Returns all user bills based on their UserName
/// </summary>
/// <param name="UserName"></param>
/// <returns></returns>
public List<Bill> GetBills(string UserName)
{
BillsEntities be = new BillsEntities();
var q = from b in be.Bills
where b.UserName == UserName
orderby b.DueDate
select new { b.DueDate, b.Name, b.PaymentAmount, b.URL };
List<Bill> billList = q.ToList();
return billList;
}
}
We can't really tell for sure, but I suspect you could do:
var q = from b in be.Bills
where b.UserName == UserName
orderby b.DueDate
select new { b.DueDate, b.Name, b.PaymentAmount, b.URL };
return q.AsEnumerable()
.Select(b => new Bill { DueDate = b.DueDate,
Name = b.Name,
PaymentAmount = b.PaymentAmount,
URL = b.URL })
.ToList();
In other words, pull the data from the database as anonymous types, but then return a list of "manually created entities" with the relevant properties copied over.
As @Jon Skeet said, we don't know what a Bill
looks like, but going from context, to make this work you need:
public List<Bill> GetBills(string UserName)
{
BillsEntities be = new BillsEntities();
return new List<Bill>(from b in be.Bills
where b.UserName == UserName
orderby b.DueDate
select new Bill {
DueDate = b.DueDate,
Name = b.Name,
PaymentAmount = b.PaymentAmount,
Url = b.URL
});
}
This assumes that the properties you selected mirror the exact properties in your Bill
class and that there won't be any null reference exceptions or bad constructor arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With