个性化阅读
专注于IT技术分析

asp.net mvc entity框架

本文概述

它是一个数据访问框架,用于在Visual Studio中创建和测试数据。它是.NET Framework和Visual Studio的一部分。最新的软件包作为Entity Framework NuGet软件包提供。最新版本是Entity Framework 6.0。

我们在ASP.NET MVC应用程序中使用它。首先,我们将创建一个项目,然后向其中添加模型。

此示例需要以下工具和技术:

  • Visual Studio 2017
  • .NET 4.5
  • 实体框架6.0
  1. 创建一个MVC项目

创建迁移

要创建迁移,请通过查看->其他窗口-> Package Manager Console打开Package Manager控制台。在程序包管理器控制台中,运行以下命令。

enable-migrations -ContextTypeName MvcEntityDemo.Models.RecordContext

我们在以下屏幕截图中执行此命令。

执行此命令后,框架在项目中创建一个Migration文件夹,并在Configuration.cs文件中创建。

我们正在使用以下代码更新此文件。

// Configuration.cs

namespace MvcEntityDemo.Migrations
{
    using MvcEntityDemo.Models;
    using System.Collections.Generic;
    using System.Data.Entity.Migrations;
    internal sealed class Configuration : DbMigrationsConfiguration<MvcEntityDemo.Models.RecordContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }
        protected override void Seed(MvcEntityDemo.Models.RecordContext context)
        {
            var students = new List<Student>
            {
            new Student{Name="Mohan", Email="Samuai@example.com", Course="Java Technology", Contact="+25-258628"}, new Student{Name="Rohan", Email="Sam@example.com", Course=".NET Technology", Contact="+25-258694"}, new Student{Name="John", Email="Max@example.com", Course="Java Technology", Contact="+25-258999"}, new Student{Name="Saba", Email="saba@example.com", Course="Linux Administration", Contact="+25-258111"}, };
            students.ForEach(s => context.Students.Add(s));
            context.SaveChanges();
        }

        }
    }
}

保存此文件并在程序包管理器控制台中运行以下两个命令。

PM> add-migration initial

之后,也运行

PM> update-database.

此命令将在迁移文件夹中为项目创建缩写。

创建支架以在网页上显示数据。

选择并添加支架。

添加控制器并提供详细信息以创建视图。


控制者

添加了一个新的StudentsController,其中包含一些自动生成的代码,如下所示。

// StudentsController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MvcEntityDemo.Models;
namespace MvcEntityDemo.Controllers
{
    public class StudentsController : Controller
    {
        private RecordContext db = new RecordContext();
        // GET: Students
        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }

        // GET: Students/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
        // GET: Students/Create
        public ActionResult Create()
        {
            return View();
        }
        // POST: Students/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID, Name, Email, Course, Contact")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }
        // GET: Students/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
        // POST: Students/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID, Name, Email, Course, Contact")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }
        // GET: Students/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
        // POST: Students/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

在视图文件夹中创建的学生文件夹。该文件夹包含一些自动生成的文件,如索引,创建,删除等。索引文件包含以下代码。

// Index.cshtml

@model IEnumerable<MvcEntityDemo.Models.Student>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Course)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Contact)
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Course)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Contact)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}
</table>

按Ctrl F5运行此文件,然后将产生以下输出。

赞(0)
未经允许不得转载:srcmini » asp.net mvc entity框架

评论 抢沙发

评论前必须登录!