gpt4 book ai didi

c# - 在我的控制台应用程序中调用 Entity Framework 类

转载 作者:行者123 更新时间:2023-11-30 23:31:02 26 4
gpt4 key购买 nike

我使用 Visual Studio 2012 创建了一个新的控制台应用程序,并使用 Entity Framework 映射了我的数据库表。现在,当我使用 MVC 等 Web 应用程序时,我通常会执行以下操作,即创建一个表示实体的新对象并引用所有可用实体:

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 block 来在我的控制台应用程序中引用 Entity Framework 类,如下所示:

class Program
{
static void Main(string[] args)
{
using (SEntities sd = new SEntities())
{
sd.Levels.Add(new Level() { Name = "from CA" });
sd.SaveChanges();
}
}
}

所以我的问题是,为什么我不能遵循第一种方法,因为将整个方法包装在一个 using block 中听起来并不奇怪?

最佳答案

问题是您正试图在静态方法中使用非静态字段。一个没有在静态方法范围内声明的更具体一点。 using block 不是导致第二个代码块工作的原因。它起作用的原因是因为您在静态方法内部而不是外部有非静态字段。

但是,实际上您应该使用 using block ,因为这将确保释放上下文。

关于c# - 在我的控制台应用程序中调用 Entity Framework 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34756393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com