Answered by:
how to insert data using entity framework 6.0 in asp.net C#

Question
-
User-1647172364 posted
Hlo professionals!
I want to insert data using entity framework 6.0 in asp.net c#.
Friday, June 12, 2020 5:44 AM
Answers
-
User1686398519 posted
Hi, sanam13
If you can successfully connect to the database, you can refer to the simple example I gave.
Note:
- For how to connect to the database, you can refer to this link.
- To implement CRUD using EF, you can refer to this link.
Model3(This is a database context.)
public class Model3 : DbContext { public Model3() : base("name=Model3") { } public DbSet<TestModel> TestModels { get; set; } }
Controller
public Model3 db = new Model3(); public ActionResult Add() { return View(); } [HttpPost] public ActionResult Add(TestModel testModel) { if (testModel != null) { try { db.TestModels.Add(testModel); db.SaveChanges(); ViewBag.SUCCESS ="SUCCESS"; } catch(Exception e) { ViewBag.ERROR = e.Message; } } return View(); }
Add
@model WebApplication3.Models.TestModel @{ ViewBag.Title = "Add"; } <h2>Add</h2> @ViewBag.SUCCESS @ViewBag.ERROR @using (Html.BeginForm("Add", "Test3")) { @Html.DisplayNameFor(m => m.content) @Html.TextBoxFor(m => m.content) <button type="submit">submit</button> }
Here is the result.
Best Regards,YihuiSun
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, June 12, 2020 8:52 AM
All replies
-
User753101303 posted
Hi,
You could start with the available documentation at https://docs.microsoft.com/en-us/ef/ or https://www.learnentityframeworkcore.com/
Forums are better suited for solving a particular problem you are running into rather than for learning something from scratch...
Friday, June 12, 2020 7:48 AM -
User1686398519 posted
Hi, sanam13
If you can successfully connect to the database, you can refer to the simple example I gave.
Note:
- For how to connect to the database, you can refer to this link.
- To implement CRUD using EF, you can refer to this link.
Model3(This is a database context.)
public class Model3 : DbContext { public Model3() : base("name=Model3") { } public DbSet<TestModel> TestModels { get; set; } }
Controller
public Model3 db = new Model3(); public ActionResult Add() { return View(); } [HttpPost] public ActionResult Add(TestModel testModel) { if (testModel != null) { try { db.TestModels.Add(testModel); db.SaveChanges(); ViewBag.SUCCESS ="SUCCESS"; } catch(Exception e) { ViewBag.ERROR = e.Message; } } return View(); }
Add
@model WebApplication3.Models.TestModel @{ ViewBag.Title = "Add"; } <h2>Add</h2> @ViewBag.SUCCESS @ViewBag.ERROR @using (Html.BeginForm("Add", "Test3")) { @Html.DisplayNameFor(m => m.content) @Html.TextBoxFor(m => m.content) <button type="submit">submit</button> }
Here is the result.
Best Regards,YihuiSun
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, June 12, 2020 8:52 AM -
User-1647172364 posted
And how to update data using entity framework in asp.net C #
Friday, June 12, 2020 11:27 AM