C# 连接关闭,但我不知道如何打开实体框架

C# 连接关闭,但我不知道如何打开实体框架,c#,entity-framework,C#,Entity Framework,我向数据库查询conexion类中的内容在哪里 public class DBConext:DbContext { public DBConext():base("myconnectionstring")//connection is correctly perfect { } public DbSet<persona> personas{get; set;} } 在我的表格里我有这个 @model MvcApplication4.Mode

我向数据库查询conexion类中的内容在哪里

public class DBConext:DbContext 
{


    public DBConext():base("myconnectionstring")//connection is correctly perfect
    {

    }

    public DbSet<persona> personas{get; set;}
}
在我的表格里我有这个

@model MvcApplication4.Models.accesslayer.persona

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @using(Html.BeginForm()) 
        {
            @Html.TextBoxFor(x=>x.nombre)
            @Html.TextBoxFor(x => x.apellido)
            @Html.TextBoxFor(x => x.ocupacion)
            <input type="submit" value="Enviar" />
        }
    </div>
</body>
</html>
但当我单击“提交”时,出现一个错误并显示:异常详细信息:

System.NullReferenceException: Object reference not set to an instance of an object.
Source File: C:\dev\vsprojects\MvcApplication4\MvcApplication4\Controllers\HomeController.cs    Line: 35 
确切地说,db.personas.add(persn)在哪里?我不明白。一位朋友告诉我数据库已关闭,但我认为实体框架没有打开和关闭功能。我也试过了,但没有效果。
建议?

当您想使用您的
上下文时,请执行以下操作:

public ActionResult insertar(persona)
{
    using (var context = new DBConext())
    {
        context.personas.Add(persona);
        context.SaveChanges();

        return RedirectToAction("Index");
    }
}

这将打开上下文和所有附属列表,然后您可以使用
语句使用
中上下文中的任何内容。

在使用DbContext的构造函数时,您是在输入完整连接字符串还是命名实例?
System.NullReferenceException: Object reference not set to an instance of an object.
Source File: C:\dev\vsprojects\MvcApplication4\MvcApplication4\Controllers\HomeController.cs    Line: 35 
public ActionResult insertar(persona)
{
    using (var context = new DBConext())
    {
        context.personas.Add(persona);
        context.SaveChanges();

        return RedirectToAction("Index");
    }
}