在C#中,为了简化Model代码,我们可以采用以下几种方法:
public class User
{
[Required(ErrorMessage = "用户名不能为空")]
[StringLength(100, ErrorMessage = "用户名长度不能超过100个字符")]
public string UserName { get; set; }
[Required(ErrorMessage = "密码不能为空")]
[StringLength(100, ErrorMessage = "密码长度不能超过100个字符")]
public string Password { get; set; }
}
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
然后,创建一个Mapper配置类:
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<User, UserDto>();
CreateMap<UserDto, User>();
}
}
接下来,在Startup.cs中注册Mapper:
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(typeof(MappingProfile));
}
最后,使用AutoMapper进行对象映射:
public class UserController : Controller
{
private readonly IMapper _mapper;
public UserController(IMapper mapper)
{
_mapper = mapper;
}
public IActionResult Create(UserDto userDto)
{
var user = _mapper.Map<User>(userDto);
// 保存用户并返回响应
}
}
public class UserController : Controller
{
private readonly UserContext _context;
public UserController(UserContext context)
{
_context = context;
}
public IActionResult Index()
{
var users = _context.Users
.Where(u => u.IsActive)
.OrderBy(u => u.UserName)
.ToList();
return View(users);
}
}
通过使用这些方法,我们可以简化C# Model代码,提高代码的可读性和可维护性。