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

MVC+EF数据处理

时间:2015-08-13 17:14:43      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcTable.Models;
 
namespace MvcTable.Controllers
{
    public class InternHomeController : Controller
    {
        //
        // GET: /InternHome/
        WanceMISEntities MISData = new WanceMISEntities();
        public ActionResult Index()
        {
            return View(GetAllHomes());
        }
        private IEnumerable<Home> GetAllHomes()
        {
           return  MISData.Home.AsEnumerable<Home>();
        }
        //
        // GET: /InternHome/Details/5
 
        public ActionResult Details(string id)
        {
            
          return View(MISData.Home.First(s => s.HomeID == id));//用Fist()方法查询
           
        }
 
        //
        // GET: /InternHome/Create
 
        public ActionResult Create()
        {
            Home home = new Home();
            home.HomeID = Guid.NewGuid().ToString();//自动生成随机数
            return View(home);
        } 

        //
        // POST: /InternHome/Create
 
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Home home)
        {
            try
            {
                // TODO: Add insert logic here
                if (AddHomeInfo(home) > 0)
                    return RedirectToAction("Index");
                else
                    return View();
            }
            catch
            {
                return View();
            }
        }
        private int AddHomeInfo(Home home)
        {
            MISData.AddObject("WanceMISEntities.Home", home);//添加数据
            return MISData.SaveChanges();//提交数据
        }
        public ActionResult Delete(string id)//删除数据
        {
            MISData.DeleteObject(MISData.Home.First(s => s.HomeID == id));
            MISData.SaveChanges();
            return RedirectToAction("Index");//重定向页面
        }
        //
        // GET: /InternHome/Edit/5
         
        public ActionResult Edit(string id)
        {
            return View(MISData.Home.First(s=>s.HomeID==id));
        }
 
        //
        // POST: /InternHome/Edit/5
 
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(string id, Home home)
        {
            try
            {
                // TODO: Add update logic here
                MISData.Home.First(s => s.HomeID == id);//需要先查一遍使内存中有数据
                MISData.ApplyPropertyChanges("WanceMISEntities.Home", home);//把内存中的数据覆盖掉
                MISData.SaveChanges() > 0
                return RedirectToAction("Index");
                
            }
            catch
            {
                return View();
            }
        }
    }
}

 

MVC+EF数据处理

标签:

原文地址:http://www.cnblogs.com/275147378abc/p/4727469.html

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