码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-08-26 17:12:42      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

本人亲身使用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]

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

技术分享

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

标签:

原文地址:http://www.cnblogs.com/LoveQin/p/4760943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!