我已经使用Visual Studio 2012创建了一个新的控制台应用程序,并使用实体框架映射了我的数据库表。现在我用做到以下几点,当我与Web应用程序,如MVC的工作,是要创建一个表示实体和参考所有可用的实体一个新的对象:在我的控制台应用程序内调用实体框架类
class Program
{
SEntities sd = new SEntities();
static void Main(string[] args)
{
sd.Levels.Add(new Level() { Name = "from CA" });
sd.SaveChanges();
}
}
,但这将引发以下错误:
An object reference is required for the non-static field, method, or property 'ConsoleApplication1.Program.sd' .....\ConsoleApplication1\Program.cs 16 17 ConsoleApplication1
我读了一些文章,看来我需要通过打开using
块引用我的控制台应用程序中的实体框架类,如下所示:
class Program
{
static void Main(string[] args)
{
using (SEntities sd = new SEntities())
{
sd.Levels.Add(new Level() { Name = "from CA" });
sd.SaveChanges();
}
}
}
所以我的问题是,为什么我不能按照第一种方法将整个方法封装在使用块声音中并不奇怪?
好的我明白了你的观点,那么有没有办法避免使用“使用”块? –
'using'块确保调用上下文的Dispose()方法;释放非托管资源。在所有的现实中,你不必使用它,但最佳实践将另有说明。另一种选择是“try/finally”。在'finally'手动调用'Dispose()'。 –
但我无法在我的情况下引用“sd”,除非我在我的使用块中传递实体类。 –