MVC3.0 EF增删改查的封装类

本人亲身使用EF CodeFirst,因为增删改查都是使用EF内置的一些方法,我想把它封装到一个类调用就行了。结合网上的资料和自己的整理,若有不对的地方望斧正,感激不尽。直接上代码吧。我就用新闻的增删改查做例子。

这是项目的整个结构图:

Views文件夹的文件

1.先看Index.cshtml页面的代码把

Index.cshtml(列表页面)

@model IEnumerable<NewsMvc.Models.News>
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>首页</title>
    <style type="text/css">
        body
        {
            font-size: 12pt;
        }
        a
        {
            text-decoration:none;
        }
    </style>
</head>
<body>
    <p>
        @Html.ActionLink("添加", "Create")
    </p>
    <table>
        <tr>
            <th>
                标题
            </th>
            <th>
                添加人
            </th>
            <th>
                内容
            </th>
            <th>
                添加时间
            </th>
            <th>
            </th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Title)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.AddUser)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Content)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.AddDate)
                </td>
                <td>
                    @Html.ActionLink("编辑", "Edit", new { id = item.Id }) |
                    @Html.ActionLink("查看", "Details", new { id = item.Id }) |
                    @Html.ActionLink("删除", "Delete", new { id = item.Id })
                    <a href="News/Edit/@item.Id">编辑</a>
                    <a href="News/Delete/@item.Id" onclick="return confirm(‘删除后无法恢复,是否删除?‘)">X</a>
                </td>
            </tr>
        }
    </table>
</body>
</html>

2.Create.cshtml(添加页面)。这里引用了一个日历控件,链接:http://www.my97.net/dp/down.asp

<!DOCTYPE html>
<html>
<head>
    <title>添加新闻</title>
    <script src="../../Scripts/datePicker/WdatePicker.js" type="text/javascript"></script>
</head>
<body>
    <form method="post">
    <fieldset>
        <legend>新闻信息</legend>
        <div class="editor-label">
            标题
        </div>
        <div class="editor-field">
            <input type="text" id="news_title" name="news_title" />
        </div>
        <div class="editor-label">
            添加人
        </div>
        <div class="editor-field">
            <input type="text" id="news_adduers" name="news_adduers" />
        </div>
        <div class="editor-label">
            内容
        </div>
        <div class="editor-field">
            <input type="text" id="news_content" name="news_content" />
        </div>
        <div class="editor-label">
            添加时间
        </div>
        <div class="editor-field">
            <input type="text" id="news_adddate" name="news_adddate" onfocus="WdatePicker({dateFmt:‘yyyy-MM-dd‘,readOnly:true})" />
        </div>
        <p>
            <input type="submit" value="添 加" />
        </p>
        <div>
            @Html.ActionLink("返回列表", "Index")
            <a href="Index">返回列表</a>
        </div>
    </fieldset>
    </form>
</body>
</html>

3. Edit.cshtml(修改页面)

@model NewsMvc.Models.News

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Edit</title>
</head>
<body>
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    <script src="../../Scripts/datePicker/WdatePicker.js" type="text/javascript"></script>

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>News</legend>

            @Html.HiddenFor(model => model.Id)

            <div class="editor-label">
                @Html.LabelFor(model => model.Title)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Title)
                @Html.ValidationMessageFor(model => model.Title)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.AddUser)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.AddUser)
                @Html.ValidationMessageFor(model => model.AddUser)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.Content)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Content)
                @Html.ValidationMessageFor(model => model.Content)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.AddDate)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.AddDate, new { onfocus = "WdatePicker({dateFmt:‘yyyy-MM-dd‘,readOnly:true})" })
                @Html.ValidationMessageFor(model => model.AddDate)
            </div>

            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

Models的文件:

1.News.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace NewsMvc.Models
{
    public class News
    {
        [Display(Name = "编号")]
        public int Id { get; set; }
        [Required(ErrorMessage = "标题必填")]
        [Display(Name = "标题")]
        public string Title { get; set; }
        [Display(Name = "添加人")]
        public string AddUser { get; set; }
        [Display(Name = "内容")]
        public string Content { get; set; }
        [Display(Name = "添加时间")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
        public DateTime AddDate { get; set; }
        [Display(Name = "备注")]
        public string Remark { get; set; }
        public string tes { get; set; }
    }
}

2.NewsDbContent.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace NewsMvc.Models
{
    public class NewsDbContent : DbContext
    {
        public DbSet<News> Newss { get; set; }
        public DbSet<NewsType> NewsTypes { get; set; }
    }

}

3.BaseOption.cs(重点来了,这就是封装了EF的增删改查的公共类)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace NewsMvc.Models
{
    public class BaseOption<T> where T : class
    {
        NewsDbContent ns_db = new NewsDbContent();
        public void Add(T entity)
        {
            ns_db.Entry<T>(entity).State = EntityState.Added;
            ns_db.SaveChanges();
        }
        //修改
        public void Update(T entity)
        {
            ns_db.Set<T>().Attach(entity);
            ns_db.Entry<T>(entity).State = EntityState.Modified;
            ns_db.SaveChanges();
        }
        //删除
        public void Delete(T entity)
        {
            ns_db.Set<T>().Attach(entity);
            ns_db.Entry<T>(entity).State = EntityState.Deleted;
            ns_db.SaveChanges();
        }
        //查询集合
        public List<T> getlist(T entity)
        {
            return ns_db.Set<T>().ToList();
        }
        //根据Id返回查询的集合
        public T FindById(params object[] keyValues)
        {
            return ns_db.Set<T>().Find(keyValues);
        }
    }
}

如何使用这个呢,以下是例子:

Controllers文件夹下的文件

NewsController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NewsMvc.Models;
using System.Text;
namespace NewsMvc.Controllers
{
    public class NewsController : Controller
    {
        BaseOption<News> bs = new BaseOption<News>();
        //列表页面
        public ActionResult Index()
        {
            News ns = new News();
            return View(bs.getlist(ns));
        }
        //添加
        public ActionResult Create()
        {
            return View();
        }
        //添加
        [HttpPost]
        public ActionResult Create(News ns)
        {
            ns.Title = Request.Form["news_title"].ToString().Trim();
            ns.AddUser = Request.Form["news_adduers"].ToString().Trim();
            ns.Content = Request.Form["news_content"].ToString().Trim();
            ns.AddDate = DateTime.Parse(Request.Form["news_adddate"].ToString().Trim());
            bs.Add(ns);
            return RedirectToAction("Index");
        }
        //修改
        News ns = new News();
        public ActionResult Edit(int id)
        {
            ns = bs.FindById(id);
            return View(ns);
        }
        //修改
        [HttpPost]
        public ActionResult Edit(News ns)
        {
            bs.Update(ns);
            return RedirectToAction("Index");
        }
        //删除
        public ActionResult Delete(int id)
        {
            ns = bs.FindById(id);
            bs.Delete(ns);
            return RedirectToAction("Index");
        }
    }
}

Web.config文件

<?xml version="1.0" encoding="utf-8"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
<configuration>
  <configSections>

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <connectionStrings>
    <add name="NewsDbContent" connectionString="Data Source=.;Initial Catalog=News;Integrated Security=true;" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Sql数据库代码:(本人使用的sa帐号登录的咯)

数据库名字:News

news表代码:

USE [News]
GO
/****** 对象:  Table [dbo].[News]    脚本日期: 08/26/2015 16:38:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[News](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Title] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NOT NULL,
    [AddUser] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
    [Content] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
    [AddDate] [datetime] NOT NULL,
    [Remark] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
    [tes] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK_dbo.News] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

由于不能上传项目,所以需要的留言给我吧。

时间: 2024-08-29 05:16:22

MVC3.0 EF增删改查的封装类的相关文章

WPF MVVM+EF增删改查 简单示例(二) 1对1 映射

WPF MVVM+EF增删改查 简单示例(一)实现了对学生信息的管理. 现在需求发生变更,在录入学生资料的时候同时需要录入学生的图片信息,并且一名学生只能有一张图片资料.并可对学生的图片资料进行更新. 添加了那些功能,先看看效果图: 第一步:添加实体类StudentPhotoEntity.cs public class StudentPhotoEntity { public int StudentId { get; set; } public byte[] StudentPhoto { get;

EF增删改查+使用Expression进行排序分页

注:以下部分来自<ASP.NET MVC 企业级实战>一书的摘抄和改写以及部分个人学习心得. EF简单增删改查 增加 public static int Add() { using (NorthwindEntities db=new NorthwindEntities()) { Customers cs2 = new Customers { CustomerID = "11", ContactName="aa4444sa", Address="

YII2.0 数据库增删改查

/*==================== dkhBaseModel 数据库增删改查方法 start ================================*/ //新增一条数据 public function baseInsertData($data){ if(!is_array($data)) {return $this->setError(['errmsg'=>'data Error']);}; $db = \Yii::$app->db; $ok = $db->c

构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(5)-EF增删改查by糟糕的代码

上一讲我们创建了一系列的解决方案,我们通过一个例子来看看层与层之间的关系. 我们把Controllers分离出来了BLL层和DAL层 BLL专注于业务上的处理 DAL专注于数据访问层的处理 而Controller跟清楚的与View交互 我们上一讲已经在EF添加了一个实体SysSample 下面我们创建IDAL,DAL,IBLL,BLL的代码吧 using App.Models; using System.Linq; namespace App.IDAL { public interface IS

webapi+EF(增删改查)

第一步,Model建立Ado.net实体模型. 第二部,Controller建立增删查改方法 public static HttpResponseMessage toJson(Object obj)        {            String str;            if (obj is String || obj is Char)            {                str = obj.ToString();            }           

EF 增删改查 泛型方法

1.定义泛型类 namespace Crm.Data.Logic.Repository{    public abstract class AbstractRepository<TC, T> : IDisposable        where TC : DbContext, new()        where T : class    {        private TC _entities = new TC();        private bool _disposed;      

EF增删改查

//查询 //查询指定字符串出现的个数,类似于模糊查询select count(*) from Book where Name like '%字符串%' db.Book.Where(x => x.Name.Contains(txtName.Text.Trim())).Count(); //接收查询的数据 List<Book> bk = db.Book.ToList(); dataGridView1.DataSource = bk; //添加 Book bk = new Book(){ A

EF CodeFirst增删改查之‘CRUD’

最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精    本篇旨在学习EF增删改查四大操作 上一节讲述了EF CodeFirst 创建数据库,本节继续引用上一节的相关类学习EF的CRUD操作 废话少说,直接上要点,上一节中的模型类我作了如下修改: using System; using System.Collections.Generic; using System.ComponentModel.Data

[EF]使用EF简单增删改查

目录 认识EF 添加数据 删除数据 修改数据 查询数据 总结 认识EF ADO.NET Entity Framework 是微软以ADO.NET为基础所发展出来的对象关系对伊(O/R Mapping)解决方案,早起被称为ObjectSpage,最新版本EF6. 实体框架Entity Framework是ADO.NET中的一组支持面向数据的软件应用程序的技术.是微软的一个ORM框架. 什么是O/R Mapping 广义上,ORM指的是面向对象模型和关系数据库的数据结构之间的相互转换. 狭义上,OR