我对数据库进行查询,我的 conexion 类中的内容在哪里
public class DBConext:DbContext
{
public DBConext():base("myconnectionstring")//connection is correctly perfect
{
}
public DbSet<persona> personas{get; set;}
}
在我的班级角色中,我有这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication4.Models.accesslayer
{
public class persona
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int idCliente { get; set; }
public string nombre { get; set; }
public string apellido { get; set; }
public string ocupacion { 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>
和控制器
[HttpPost, ActionName("Index")]
public ActionResult insertar(persona prsn)
{
var db = conexion.StringCon;
db.personas.Add(prsn);
db.Save();
return RedirectToAction("Index");
}
但是当我点击提交时,出现一个错误并说:异常详细信息:
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)
?我不明白。有朋友告诉我数据库关闭了,但我认为实体框架没有打开和关闭。我也尝试过,但没有任何效果。建议?