我将ASP.NET Core 2.0
与EntityFramwork
结合使用DataAnotations
。
当我需要从我的数据库更新模型时,我正在执行:
PM: Scaffold-DbContext "Server=localhost;Database=MyDb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force
...从模型中删除DataAnotations。
我使用这样的ViewModel
找到了解决方法:
public class Company
{
public Guid CompanyId { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
public class VmCompany : Company
{
[Required, DataType(DataType.EmailAddress)]
public new string Email { get; set; }
}
在 Create.cshtml.cs 中,我绑定了ViewModel VmCompany
:
[BindProperty]
public VmCompany VmCompany { get; set; }
public async Task<IActionResult> OnGetAsync()
{
...
}
使用ViewModel VmCompany
Create.cshtml
<form method="post">
<input type="hidden" asp-for="VmCompany.CompanyId" />
<div class="form-group">
<label asp-for="VmCompany.Name">Name</label>
<input asp-for="VmCompany.Name" class="form-control" />
</div>
<div class="form-group">
<label asp-for="VmCompany.Phone">Phone</label>
<input asp-for="VmCompany.Phone" class="form-control" />
</div>
...
<div class="text-danger" asp-validation-summary="All"></div>
</form>
最后在Page POST:
我将数据从ViewModel
插入到模型中 public async Task<IActionResult> OnPostAsync()
{
var company = new Models.Company
{
Name = VmCompany.Name,
CompanyId = VmCompany.CompanyId,
Email = VmCompany.Email,
Phone = VmCompany.Phone,
};
_db.Company.Add(company);
await _db.SaveChangesAsync();
return RedirectToPage("/company/list");
}
它有效,但它是正确的方法吗?是否有更简单的方法来保持模型DataAnotations?