I have an EF Core partial class from our database table that includes data annotations, such as Required.
I also have a Metadata class and another partial that as far as I can tell 'should' be overwriting those EF annotations, but that is not happening.
snippet of EF class:
namespace Business
{
public partial class Staff
{
[Key]
public int ID { get; set; }
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string LastName { get; set; }
}
}
snippet of Metadata class:
namespace Business
{
/// <summary>
/// The Staff object
/// </summary>
public class StaffMD
{
[DisplayName("ID")]
[Description("The unique key for a Staff")]
[Required(ErrorMessage = "ID is required")]
public int ID { get; set; }
[DisplayName("First Name")]
[Description("The First Name for a Staff")]
[Required(ErrorMessage = "First Name is required")]
[MaxLength(50, ErrorMessage = "First Name can only be {1} characters")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
[Description("The Last Name for a Staff")]
[Required(ErrorMessage = "Last Name is required")]
[MaxLength(50, ErrorMessage = "Last Name can only be {1} characters")]
public string LastName { get; set; }
}
[ModelMetadataType(typeof(StaffMD))]
public partial class Staff
{
}
}
snippet of view:
@model Staff
@using Business;
@{
ViewData["Title"] = "Create - Staff";
}
@using (Html.BeginForm("Create", "Staff", null, FormMethod.Post, true, null))
{
<p>
<div class="formContainer" id="formContainerParent">
<div class="formContainer-item">
<h2 class="formContainer-header" id="formHeadingOne">
<label class="formContainer-headerContent">
Create Staff
</label>
</h2>
<div id="formContentOne" class="formContainer-body" aria-labelledby="formHeadingOne">
<div class="formContainer-bodyContent">
<div class="row">
<div class="col-md-3">
<div>
@Html.AccessibleRequiredLabelFor(model => model.FirstName, null, null, new { @class = "control-label" })
</div>
<div>
@Html.TextBoxFor(model => model.FirstName, null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="col-md-3">
<div>
@Html.AccessibleRequiredLabelFor(model => model.LastName, null, null, new { @class = "control-label" })
</div>
<div>
@Html.TextBoxFor(model => model.LastName, null, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</p>
}
Image of application using 'default' Required message from EF core attribute