当我将表添加到我的数据库时,我正在寻找一种提高生产力的方法。通常,当我添加新表时,我必须执行以下步骤。
- 将表添加到数据库(简单)
- 创建相应的 EF Code First 类。(我不使用数据库迁移)
- 创建一个与 #2 中创建的 EF 类匹配的 POCO 模型。
- 创建存储库类
- 为 CQRS 模式创建命令和处理程序
- 为新创建的类创建 AutoMapper 映射
我最近创建了一个新网站,要求首先使用 EF 数据库,我看到了它是如何使用 tt 文件生成类的。这让我想到我可以以某种方式使用这些模板(新模板)来生成基本 CRUD 操作的所有标准支持项。麻烦的是我没有创建这些模板的经验,也不知道从哪里开始。
要生成的示例代码:
存储库
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public interface IUsersRepository : IRepository<Users>
{
}
public class UsersRepository : RepositoryBase<Users>, IUsersRepository
{
    public UsersRepository(IDatabaseFactory databaseFactory)
        : base(databaseFactory)
    {
    }
}
基于从 EDMX(或 Code First)生成的实体的基本模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class User 
{
    public int UserId { get; set; }
    public string UserRole { get; set; }
    public string UserName { get; set; }
}
命令
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class AddUpdateUserPayoutCommand : CommandBase, ICommand
{
    public int UserId { get; set; }
    public string UserRole { get; set; }
    public string UserName { get; set; }
}
命令处理程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class AddUpdateUserHandler: ICommandHandler<AddUpdateUserCommand>
{
    private readonly IUsersRepository _repository;
    private readonly IUnitOfWork _unitOfWork;
    public AddUpdateUserPayoutHandler(IUsersRepository repository, IUnitOfWork unitOfWork)
    {
        _repository = repository;
        _unitOfWork = unitOfWork;
    }
    public ICommandResult Execute(AddUpdateUserCommand command)
    {
        Users entity;
        if (command.UserId == 0)
        {
            entity = AutoMapper.Mapper.Map<Users>(command);
            _repository.Add(entity);
        }
        else
        {
            entity = _repository.Get(x=>x.UserId==command.UserId);
            entity = AutoMapper.Mapper.Map<Users>(command);
            _repository.Update(entity);
        }
        _unitOfWork.Commit(command.UserId);         
        return new CommandResult(true,entity.UserId);
    }
}
Automapper Maps - 放置在 app_start
Mapper.CreateMap<User, AddUpdateUserCommand>();