public interface IRepository<TEntity> : IRepository<TEntity,Guid> where TEntity : class, IAggregateRoot, IBaseEntity
{
}
public interface IRepository<TEntity,Tkey> where TEntity : class, IAggregateRoot<Tkey>,IBaseEntity<Tkey>
{
TEntity Add(TEntity t);
int Count();
Task<int> CountAsync();
void Delete(TEntity entity);
TEntity Find(Expression<Func<TEntity, bool>> match);
IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> match);
Task<IEnumerable<TEntity>> FindAllAsync(Expression<Func<TEntity, bool>> match);
Task<TEntity> FindAsync(Expression<Func<TEntity, bool>> match);
TEntity Get(int id);
IEnumerable<TEntity> GetAll();
Task<List<TEntity>> GetAllAsyn();
Task<TEntity> GetAsync(int id);
void Update(TEntity PoEntity, TEntity VoEntity);
}
public class Repository<TEntity> : Repository<TEntity, Guid>,IRepository<TEntity> where TEntity : class, IAggregateRoot, IBaseEntity
{
public Repository(UnitOfWorkDbContext dbDbContext) : base(dbDbContext)
{
}
}
public class Repository<TEntity, Tkey> : IRepository<TEntity, Tkey> where TEntity : class, IAggregateRoot<Tkey>, IBaseEntity<Tkey>
{
private readonly UnitOfWorkDbContext _dbContext;
public virtual DbSet<TEntity> Table => _dbContext.Set<TEntity>();
public Repository(UnitOfWorkDbContext dbDbContext)
{
_dbContext = dbDbContext;
}
public IEnumerable<TEntity> GetAll()
{
return Table.AsNoTracking().ToList();
}
public virtual async Task<IEnumerable<TEntity>> GetAllAsyn(CancellationToken cancellationToken = default(CancellationToken))
{
return await Table.AsNoTracking().ToListAsync(cancellationToken);
}
public virtual TEntity Get(int id)
{
return Table.Find(id);
}
public virtual async Task<TEntity> GetAsync(int id)
{
return await Table.FindAsync(id);
}
public virtual TEntity Add(TEntity entity)
{
return Table.Add(entity).Entity;
}
public virtual TEntity Find(Expression<Func<TEntity, bool>> match)
{
return Table.SingleOrDefault(match);
}
public virtual async Task<TEntity> FindAsync(Expression<Func<TEntity, bool>> match)
{
return await Table.SingleOrDefaultAsync(match);
}
public IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> match)
{
return Table.Where(match).ToList();
}
public async Task<IEnumerable<TEntity>> FindAllAsync(Expression<Func<TEntity, bool>> match)
{
return await Table.Where(match).ToListAsync();
}
public virtual void Delete(TEntity entity)
{
Table.Remove(entity);
}
public virtual void Update(TEntity PoEntity, TEntity VoEntity)
{
_dbContext.Entry(PoEntity).CurrentValues.SetValues(VoEntity);
}
public int Count()
{
return Table.Count();
}
public async Task<int> CountAsync()
{
return await Table.CountAsync();
}
public Task<List<TEntity>> GetAllAsyn()
{
return Table.AsNoTracking().ToListAsync();
}
}
在appsettings 中增加数据库配置字符串
"ConnectionStrings": {
"SqlServerConnection": "Data source=LocalHost;Initial Catalog=MyWebData;Integrated Security=True"
}
在 web api 中Startup注入DbContext
services.AddDbContext<UnitOfWorkDbContext>(
options => options.UseSqlServer(
Configuration.GetConnectionString("SqlServerConnection"),p=>p.MigrationsAssembly("CoreWebLibrary.DB")));
注入 操作仓库等
public static void AddService(this IServiceCollection serviceCollection)
{
serviceCollection.AddTransient<IUserService, UserService>(); //逻辑层
serviceCollection.AddScoped<IUnitOfWork, UnitOfWork<UnitOfWorkDbContext>>();
//注入泛型仓储
serviceCollection.AddTransient(typeof(IRepository<>), typeof(Repository<>));
serviceCollection.AddTransient(typeof(IRepository<,>), typeof(Repository<,>));
AutoMapperHelp.InitAutoMapper(); //实例化AutoMapper
}
services.AddService()
增加一个实体类 和 对应表的关系
public enum Gender
{
男,
女
}
public enum MaritalStatus
{
未婚,
已婚,
离异
}
public class SystemUser : UpdateEntity<int>
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
public Gender Gender { get; set; }
/// <summary>
/// 年龄
/// </summary>
public ushort Age { get; set; }
/// <summary>
/// 名族
/// </summary>
public string Race { get; set; }
/// <summary>
/// 员工编号
/// </summary>
public string EmployeeNumber {get;set;}
/// <summary>
/// 婚姻状态
/// </summary>
public MaritalStatus MaritalStatus { get; set; }
/// <summary>
/// 国籍
/// </summary>
public string Nationality { get; set; }
}
public class SystemUserConfig : IEntityTypeConfiguration<SystemUser>
{
public void Configure(EntityTypeBuilder<SystemUser> systemUser)
{
systemUser.ToTable("Sys_User");
systemUser.Property(x => x.Name).IsRequired();
systemUser.Property(x => x.Gender).IsRequired();
systemUser.Property(x => x.Age).IsRequired();
systemUser.Property(x => x.Race).IsRequired();
systemUser.Property(x => x.EmployeeNumber).IsRequired().HasMaxLength(20);
systemUser.Property(x => x.MaritalStatus).IsRequired();
systemUser.Property(x => x.Nationality).IsRequired();
}
}
在控制台中输入以下命令
Add-Migration Init
update-Database Init
就会创建实例对应的表
如何使用
增加CoreWebLibrary.Service 项目
增加IUserService 和 UserService 逻辑层
public interface IUserService
{
Task<int> AddUser(SystemUser systemUser);
}
public class UserService : IUserService
{
IUnitOfWork unitOfWork;
IRepository<SystemUser, int> repository;
ILogger<UserService> log;
public UserService (IUnitOfWork unitOfWork, IRepository<SystemUser,int> repository,ILogger<UserService> log)
{
this.unitOfWork = unitOfWork;
this.repository = repository;
this.log = log;
}
public async Task<int> AddUser(SystemUser systemUser)
{
SystemUser user = repository.Add(systemUser);
int index = await unitOfWork.SaveChangesAsync();
log.Log(LogLevel.Information,$"Create User by id {user.Id}");
return index;
}
}
在web Api的控制器中增加操作方法
[MyActionFilter]
[HttpPost("AddUser")]
public async Task<IActionResult> AddUser([FromServices] IUserService userService,[FromBody] VUser vUser)
{
SystemUser systemUser = AutoMapperHelp.Map.Map<SystemUser>(vUser);
int index = await userService.AddUser(systemUser);
return Json(new VReturnMessage<int>
{
Message = "保存成功",
ReturnCode = 200,
Data = index
});
}