Frage

I am working with LINQ To SQL connection in my ASP.NET website but I have some strange problems. I created Singleton entity of DataContext for all of the using in the website but I don't really understand why the data not always updated and sometimes adding row to table failed because another entity with the same key already exists (I checked and that is no such entity).

What's the problem and there is another way to use this connection?

public class SQLConnection
{
    private LearningDBDataContext dbDataContext;

    public SQLConnection()
    {
        dbDataContext = new LearningDBDataContext();
    }

    public LearningDBDataContext GetDataContextInstance()
    {
        return dbDataContext;
    }

    public void reCreateDBConnection()
    {
        dbDataContext = new LearningDBDataContext();
    }
}
War es hilfreich?

Lösung

Definitely don't use a singleton. If you are using an IoC container then you can set the context to be shortlived - one instance of the context per request. Or in your data access layer, wrap any datacontext instantiations with a using statement to be sure that it is properly disposed of, i.e:

MyModel model;
using(var context = new LearningDBDataContext()){
     // fetch your data here
     model = ...
}
return model;

Check out this SO post and this MSDN site for more info on this subject.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top