ASP.NET 网站项目 EF 的简单操作例子:
操作代码:
using EFTest.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;namespace EFTest.Controllers
{public class DataController : Controller{//// GET: /Data/EFTestDB db = new EFTestDB();public ActionResult Index(){return View();}public string Create(){db.Room.ToList();//List<Room> Rooms = db.Room.Where(x=>x.RoomId == 1 && x.RoomName.Equals("a")).ToList();return "创建数据库";}public string Add(){Room room;for (int i = 0; i < 10;i ++ ){room = new Room();room.RoomId = i;room.RoomName = "Room" + i;room.RoomDesc = "Room Desc";List<Person> persons = new List<Person>();Person person;for (int j = 0; j < 2;j++ ){person = new Person();person.PersonId = i + j;person.PersonName = "p" + i + j;person.PersonSex = "男";persons.Add(person);}room.Persons = persons;db.Room.Add(room);}db.SaveChanges();return "添加数据";}public string Update() {Room room = db.Room.FirstOrDefault(x=>x.RoomId == 11);room.RoomName = "房间11";//db.Room.(room);db.Entry(room).State = EntityState.Modified;db.SaveChanges();return "数据已修改";}}
}