Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Repository Pattern: Creating Model Classes

Reviewing Conery's storefront, and I dont understand why he used Linqs auto-generated classes (ie Order class) and then he has another Order class defined that is not a partial class. WHen using repository pattern should one manually create the classes, and disregard Datacontext altogether?

like image 560
zsharp Avatar asked Mar 02 '23 02:03

zsharp


1 Answers

If you don't decouple your front end from the linq classes using an intermediary class, you can't control with the data context gets garbage collected. Typically with data context types of instances you want to rid of them as soon as you're done using them. Here's how you might want to do this with the linq to sql context:

using (MyDataContext data = new MyDataContext())
{
    SomeThing thing = data.Things(t => t.ID == 1);
    return thing;
}
... the MyDataContext instance is gone

With the "using" block, you're disposing of the instance of MYDataContext at the last "}". However, if you do this you'll get an error then trying to use "thing" because the data context instance is gone. If you don't dispose of the data context, it's left hanging around until it's eventually garbage collected.

If you introduce an intermediary class to decouple the linq to sql code from the calling app you can still get rid of your data context instance and return the same data (just in a different object):

using (MyDataContext data = new MyDataContext())
{
    SomeThing thing = data.Things(t => t.ID == 1);
    SometThingElse otherThing = ConvertSomethingToSomethingElse(thing);
    return otherThing;
}
... the MyDataContext instance is gone

Hope that helps.

like image 138
Ian Suttle Avatar answered Mar 12 '23 10:03

Ian Suttle