在我看来,如果您可以使用 AutoMapper 而不是复制值,那么您的第一个选择会更加简单和安全。
请参考下面使用 asp.net core 3.0 Razor Pages 的演示:
1.Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
2.创建模型(保存到数据库)和视图模型(显示在用户页面上)
public class Movie
{
public Movie()
{
Genre = "Action";
}
public int ID { get; set; }
public string Title { get; set; }
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
}
public class MovieViewModel
{
public string Title { get; set; }
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
}
3.创建AutoMapperProfile类
public class MovieProfile: Profile
{
public MovieProfile()
{
CreateMap<MovieViewModel, Movie>().ReverseMap();
}
}
4.Create.cshtml.cs
public class CreateModel : PageModel
{
private readonly ApplicationContext _context;
private readonly IMapper _mapper;
public CreateModel(ApplicationContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public IActionResult OnGet()
{
return Page();
}
[BindProperty]
public MovieViewModel MovieVM { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
Movie movie = _mapper.Map<Movie>(MovieVM);
_context.Movie.Add(movie);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
创建.cshtml
@page
@model RazorpagesCore.Pages.Movies.CreateModel
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="MovieVM.Title" class="control-label"></label>
<input asp-for="MovieVM.Title" class="form-control" />
<span asp-validation-for="MovieVM.Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="MovieVM.ReleaseDate" class="control-label"></label>
<input asp-for="MovieVM.ReleaseDate" class="form-control" />
<span asp-validation-for="MovieVM.ReleaseDate" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}