在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代碼,提高代碼的可讀性和可維護性。