asp.net mvc 三层架构的增删改查
时间: 2023-12-13 22:33:18 浏览: 149
以下是ASP.NET MVC三层架构的增删改查操作的示例代码:
1. Model层代码:
```csharp
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Title { get; set; }
}
```
2. DataAccess层代码:
```csharp
public class UserDataAccess
{
public List<User> GetAllUsers()
{
using (var context = new UserContext())
{
return context.Users.ToList();
}
}
public User GetUserById(int id)
{
using (var context = new UserContext())
{
return context.Users.FirstOrDefault(u => u.ID == id);
}
}
public void AddUser(User user)
{
using (var context = new UserContext())
{
context.Users.Add(user);
context.SaveChanges();
}
}
public void UpdateUser(User user)
{
using (var context = new UserContext())
{
var oldUser = context.Users.FirstOrDefault(u => u.ID == user.ID);
if (oldUser != null)
{
oldUser.Name = user.Name;
oldUser.Title = user.Title;
context.SaveChanges();
}
}
}
public void DeleteUser(int id)
{
using (var context = new UserContext())
{
var user = context.Users.FirstOrDefault(u => u.ID == id);
if (user != null)
{
context.Users.Remove(user);
context.SaveChanges();
}
}
}
}
```
3. Service层代码:
```csharp
public class UserService
{
private readonly UserDataAccess _userDataAccess;
public UserService()
{
_userDataAccess = new UserDataAccess();
}
public List<User> GetAllUsers()
{
return _userDataAccess.GetAllUsers();
}
public User GetUserById(int id)
{
return _userDataAccess.GetUserById(id);
}
public void AddUser(User user)
{
_userDataAccess.AddUser(user);
}
public void UpdateUser(User user)
{
_userDataAccess.UpdateUser(user);
}
public void DeleteUser(int id)
{
_userDataAccess.DeleteUser(id);
}
}
```
4. Controller层代码:
```csharp
public class UserController : Controller
{
private readonly UserService _userService;
public UserController()
{
_userService = new UserService();
}
public ActionResult Index()
{
var users = _userService.GetAllUsers();
return View(users);
}
public ActionResult Details(int id)
{
var user = _userService.GetUserById(id);
return View(user);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
_userService.AddUser(user);
return RedirectToAction("Index");
}
return View(user);
}
public ActionResult Edit(int id)
{
var user = _userService.GetUserById(id);
return View(user);
}
[HttpPost]
public ActionResult Edit(User user)
{
if (ModelState.IsValid)
{
_userService.UpdateUser(user);
return RedirectToAction("Index");
}
return View(user);
}
public ActionResult Delete(int id)
{
var user = _userService.GetUserById(id);
return View(user);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
_userService.DeleteUser(id);
return RedirectToAction("Index");
}
}
```
以上代码实现了对User表的增删改查操作,其中Model层定义了User实体类,DataAccess层实现了对User表的增删改查操作,Service层对DataAccess层进行了封装,Controller层实现了对应的Action方法,用于响应用户的请求。
阅读全文