Can't select from a SQL datasource "Cannot convert type 'NorthwindDataContext' to 'System.Idisposable'

StackOverflow https://stackoverflow.com/questions/23385958

سؤال

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?

هل كانت مفيدة؟

المحلول

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();
}

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top