Question

I'm trying to retrieve some data from a SQL server datasource. This is probably really trivial but I can't see what I am missing.

My code so far is

    public List<string> GetCountries()
    {
        using (var context = new NorthwindDataContext())
        {
            return (from c in context.Customers
                select c.Country).Distinct().ToList();
        }
    }

But visual studio is complaining with

"Cannot convert type 'NorthwindDataContext' to 'System.Idisposable'"

with regard to

new NorthwindDataContext()

it also can't seem to resolve

select c.Country

I'm using .net 4.5

can anyone suggest anything?

Was it helpful?

Solution

This is presumably because NorthwindDataContext() does not implement the IDisposable interface so you can't use it within a using() statement.

Try this instead:

public List<string> GetCountries()
{
    var context = new NorthwindDataContext();

    return (from c in context.Customers
           select c.Country).Distinct().ToList();
}

OTHER TIPS

The using statement is tied to the IDisposable interface, as explained in the MSDN docs:

Provides a convenient syntax that ensures the correct use of IDisposable objects.

This means that, after returning the list of your objects, the application will try to dispose the used objects and marking them for garbage collection. What your using will do corresponds to the following code:

try
{
    string s = myObject.Stuff();
}
finally
{
    ((IDisposable)myObject).Dispose();
}

Most probably, your NorthwindDataContext() object doesn't implement the IDisposable interface and then you have a cast error. You cannot use the using statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top