This
artilce will show you how to insert data into database using entity framework
in Asp.net mvc. This article will help on entity framework 6 insert record, Save
Form Data to Database using Model in ASP.NET.
So for this article first we will create a new table.
So for this article first we will create a new table.
Now check the data currently present in my table.
Now we will create a new asp.net mvc application and add an entity file and import your table in
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC_Demos.Models
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Section { get; set; }
public string Marks { get; set; }
}
}
|
Now we will add a controller class file and add the below
code.
using MVC_Demos.Models;
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace
MVC_Demos.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
[HttpGet]
public ActionResult
Index()
{
Student _studentModel = new Student();
return
View(_studentModel);
}
[HttpPost]
public ActionResult
Index(Student
_studentModel)
{
try
{
DemoEntities
_demoEntities = new DemoEntities();
StudentDetail stu
= new
StudentDetail();
stu.Id = _studentModel.Id;
stu.Name = _studentModel.Name;
stu.Marks = Convert.ToInt32(_studentModel.Marks);
stu.Section = _studentModel.Section;
stu.Address = _studentModel.Address;
_demoEntities.StudentDetails.Add(stu);
_demoEntities.SaveChanges();
ViewBag.Message = "Data saved
successfully.";
}
catch
{
ViewBag.Message = "Error
while saving record.";
}
return
View(_studentModel);
}
}
}
|
Now in above code just check highlighted part of the code. In above code first we have created the instance of the entity and then instance for the entity table. After creating instance I have assign the model value to entity table object.
After that I have added the entity table to the entity
object. Now I have save the entity changes.
Note: Here we need take care at in SQL table that
we must have the primary key field on out table.
Now we have done run
the application and check the output.
0 comments:
Please let me know your view