Problems using LINQ to SQL

3

I try to bring a data collection using LINQ to SQL but when I run the app it gives me an error, I'm using Visual Studio 2012 SQL Server 2008, Windows Forms app.

 private IEnumerable<Customers> ListarCustomers()
    {
        using (NorthwindDataContext db = new NorthwindDataContext())
        {
            IEnumerable<Customers> custs = db.Customers.Where(x => x.City == "Rio de Janeiro")
                .Select(x => new Customers() {CustomerID = x.CustomerID, ContactName = x.ContactName, City = x.City});
            return custs.ToList();
        }
    }

The error is as follows: The explicit construction of the entity type 'DemoDGV.Customers' in a query is not allowed. DemoDGV is the name of the project.

I also get the following error The discarded object can not be accessed. \ R \ nName of the object: 'Access to DataContext was obtained after Dispose.' ""}

    
asked by Pedro Ávila 01.11.2016 в 19:07
source

1 answer

2

I do not understand why you need to do:

.Select(x => new Customers() {CustomerID = x.CustomerID, ContactName = x.ContactName, City = x.City})

.. since the result of Where() is already an enumerable of type Customers , and as you can see in the error that you receive, you do not like that you build an instance of Customers in Select() . And it is understood, because otherwise, he would have to translate this into SQL, and he can not.

You should be able to remove the Select() , and it should work correctly:

private IEnumerable<Customers> ListarCustomers()
{
    using (NorthwindDataContext db = new NorthwindDataContext())
    {
        return db.Customers.Where(x => x.City == "Rio de Janeiro").ToList();
    }
}

Edit

If the case is that db.Customers does not return a set of type DemoDGV.Customers , and that your intention is to convert the result into a list of DemoDGV.Customers , then the key is to execute the ToList() before of Select() . In this way, the code will not try to translate the Select() in SQL, and it should work correctly.

Example:

private IEnumerable<Customers> ListarCustomers()
{
    using (NorthwindDataContext db = new NorthwindDataContext())
    {
        return db.Customers
               .Where(x => x.City == "Rio de Janeiro")
               .ToList()
               .Select(x => new Customers() {CustomerID = x.CustomerID, ContactName = x.ContactName, City = x.City});
    }
}
    
answered by 01.11.2016 / 19:11
source