前面在项目中添加了Efcore,现在使用它进行增删改查
新建类库NetCoreDemo.Services
添加接口IBaseService
public interface IBaseService { T Find<T>(string id) where T:class; IQueryable<T> Query<T>(Expression<Func<T, bool>> express) where T : class; T Insert<T>(T t) where T : class; IEnumerable<T> Insert<T>(IEnumerable<T> tList) where T : class; void Delete<T>(T t) where T : class; void Delete<T>(IEnumerable<T> tList) where T : class; void Update<T>(T t) where T : class; void Commit(); }
添加实现
public class BaseService:IBaseService { protected DbContext Context { get; private set; } public BaseService(DbContext context) { Context = context; } public T Find<T>(string id) where T : class { return this.Context.Set<T>().Find(id); } public IQueryable<T> Query<T>(Expression<Func<T, bool>> express) where T : class { return this.Context.Set<T>().Where<T>(express); } public T Insert<T>(T t) where T : class { this.Context.Set<T>().Add(t); this.Commit(); return t; } public void Delete<T>(T t) where T : class { this.Context.Set<T>().Remove(t); this.Commit(); } public void Update<T>(T t) where T : class { this.Context.Update(t); this.Commit(); } public void Commit() { this.Context.SaveChanges(); } public IEnumerable<T> Insert<T>(IEnumerable<T> tList) where T : class { this.Context.Set<T>().AddRange(tList); this.Commit(); return tList; } public void Delete<T>(IEnumerable<T> tList) where T : class { foreach(var t in tList) { this.Context.Set<T>().Attach(t); } this.Context.Set<T>().RemoveRange(tList); this.Commit(); } }
添加业务接口IUserService和UserService
public class UserService:BaseService,IUserService { public UserService(DbContext context) : base(context) { } }
主项目使用
在startup.cs中添加
#region 注册接口实现 services.AddTransient<DbContext, MyDbContext>(); services.AddTransient<IUserService, UserService>(); #endregion
在控制器中
private readonly IUserService _userService; public FirstController(ILogger<FirstController> logger, IUserService userService) { ... _userService = userService; }
public IActionResult Users()
{
var user=_userService.Find<UserInfo>("2564564");
return View(user);
}
在视图上
@model NetCoreDemo.EF.Models.UserInfo
<h1>@Model.Age @Model.Address</h1>