Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Entity Context to other methods and objects

I was wondering what is the best way to pass the context between classes. Should I be using the ref parameter or simply pass the context as a parameter? Preferably to constructor but in the case of a static method what is the best approach? I.e. performance, safety, design, etc. Is there a performance hit in passing the context as a parameter? Could possibly conflicts happen if different threads are working on the context at the same time when using references?

Main.cs

static void Main(string[] args)
{
    var context = new MyEntities();

    var myClass = new MyClass(context);
    myClass.AddPerson();
    // or
    Person.AddPerson(ref context);
}

MyClass.cs

public class MyClass
{
    public void MyClass(MyEntities context) { }

    public void AddPerson()
    {
        context.People.AddObject(new Person());
    }
}

MySecondClass.cs

public partial class Person
{
    public static AddPerson(ref MyEntities context)
    {
        // Do something
    }
}
like image 256
wonea Avatar asked Apr 22 '13 18:04

wonea


2 Answers

the ref keyword means that you are passing the pointer by reference, so changing the value of the variable will change it for the caller. AKA:

static void Main(string[] args)
{
    var context = new MyEntities();
    Person.AddPerson(ref context);

    // context is now null
}

calling:

public partial class Person
{
    public static AddPerson(ref MyEntities context)
    {
        context = null;
    }
}

In this case, you would not was to pass by reference. Remember that the variable is a pointer to the object, so simply passing it will not make a copy of the object like it would in C++.

like image 79
tster Avatar answered Nov 08 '22 00:11

tster


Using ref is totally unnecessary here. When passing around objects you're actually passing a copy of the reference (which is itself a value type that points to an object in the heap). Using the ref keyword, you're passing the "reference value" by reference (confused yet?). This means that the reference could actually be changed outside the scope of the function, which doesn't seem practical in really any circumstance and is just an opportunity for weird bugs.

like image 34
w.brian Avatar answered Nov 08 '22 01:11

w.brian