0

私は自分の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)どこですか?理解できない。友人は、データベースが閉じられていると言いましたが、エンティティ フレームワークには開閉がないと思っていました。そして、私も試してみましたが、何も機能しません。提案?

4

1 に答える 1

0

を使用する場合Contextは、次のようにします。

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

        return RedirectToAction("Index");
    }
}

usingこれにより、コンテキストとすべての関連リストが開き、このステートメント内のコンテキスト内で何でも使用できます。

于 2013-03-21T15:47:31.707 に答える