Skary
Skary

Reputation: 1362

C# LinqToSql LoadOption with pattern repository

In the project i am maintaining, i have refactoring few logic using the repository pattern over the old ORM (LinqToSql).

My problem now is sometimes i have to share DataContext across repository (this is a desirable feature) but those repository try to "steal" each other the loading option.

Here an example of my repository constructor, that receive the DataContext and build the proper loading option.

    public ArticleRepository(DataContext datacontext) : base(datacontext)
    {
        this.Name = "ArticleRepository";

        lock ( _sync )
        {
            this.Datacontext = datacontext; // --> this is done in base class, assing the shared object to the current repository.
            this.Datacontext.DeferredLoadingEnabled = false;

            DataLoadOptions options = new DataLoadOptions();
            options.LoadWith<tbl_ana_Article>(article => article.UoM);
            options.LoadWith<tbl_ana_Article>(article => article.Brand);
            this.Datacontext.LoadOptions = options;
        }
    }

But i have also OrderRepository which it's own loading option.

The problem arise when i use such repositories on the same DataContext :

using ( var context = new MyDatacontex("...") )
{
    var articleRepo = new ArticleRepository(context);
    var orderRepo = new OrderRepository(context);// <-- here the loading option are overwritten

    articleRepo.DoStuff();
    orderRepo.DoOtherStuff();

    context.SubmitChanges();
}

Now in this specific case, i can reorder operation and avoid problems but it's a very specific and fragile solution.

I don't know if i have to specify a loding option in the constructor, save it in the object, and overwrite the shared datacontex property before each datacontext use (read). Is this a good solution or there is a better one?

Upvotes: 0

Views: 111

Answers (1)

R.Abbasi
R.Abbasi

Reputation: 711

since Context is a same object, you have to prepare it before use. It's a complex scenario so you have to be warned about state of "Context Options" before any usage. If you change it before specific usage, the next usage must clear last options or set its own options. Best approach could be that you set options before usage and return it to previous state after usage so it would be all clear. But in async scenarios there is a chance that you see a behavior that you didn't expect.

An other note, some options are shared and some of them are not. For example DeferredLoadingEnabled is a shared setting and LoadWith is a specific option. You can decide to make shared setting fixated and set all specific options once in Context constructor.

Upvotes: 1

Related Questions