Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert Generic.List<AnonymousType#1> to Generic.List<BillEF.Bill>

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;
    }
}
like image 849
kyle Avatar asked Jan 19 '23 17:01

kyle


2 Answers

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.

like image 97
Jon Skeet Avatar answered Jan 30 '23 13:01

Jon Skeet


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.

like image 34
Joel Etherton Avatar answered Jan 30 '23 14:01

Joel Etherton