Reputation:
I have created a new console application using Visual Studio 2012, and I mapped my database tables using Entity Framework. Now I use to do the following when I worked with web applications such as MVC, is to create a new object representing the entities and reference all the available entities:
class Program
{
SEntities sd = new SEntities();
static void Main(string[] args)
{
sd.Levels.Add(new Level() { Name = "from CA" });
sd.SaveChanges();
}
}
but this will raise the following error:
An object reference is required for the non-static field, method, or property 'ConsoleApplication1.Program.sd' .....\ConsoleApplication1\Program.cs 16 17 ConsoleApplication1
I read some articles and it seems that I need to reference Entity Framework class inside my console application by opening a using
block as follows:
class Program
{
static void Main(string[] args)
{
using (SEntities sd = new SEntities())
{
sd.Levels.Add(new Level() { Name = "from CA" });
sd.SaveChanges();
}
}
}
So my question is, why I cannot follow the first approach as wrapping the whole method inside a using block sound not bit strange?
Upvotes: 2
Views: 1100
Reputation: 4595
The problem is that you are attempting to use a non-static field in a static method. One that is not declared in the static method's scope to be a bit more specific. The using
block is not what is causing the second block of code to work. The reason that it works is because you have the non-static field inside the static method instead of outside of it.
However, you should in fact use the using
block because that will ensure that the context is disposed.
Upvotes: 1