I'm having trouble using database first approach model validations, i read famous ASP.NET MVC 2: Model Validation by Scott Gu, but the problem is it did not work in my mvc project, I'm having my Edmx file in Project.Model class library ,and my validation class in Project.Model.Membership namespace, I don't really get the concept of a problem here. here is the code:
namespace Project.Model
//part of generated code by EF database first
public partial class Member
{
public Member()
{
this.SideDuties = new HashSet<SideDuty>();
this.Member_In_Role = new HashSet<Member_In_Role>();
this.Messages = new HashSet<Message>();
this.Messages1 = new HashSet<Message>();
}
public System.Guid mId { get; set; }
public byte MemberTypeNo { get; set; }
public string mName { get; set; }
public string mLName { get; set; }
public string mUserName { get; set; }
public string mPass { get; set; }
public Nullable<byte> MarriageStatusNo { get; set; }
public Nullable<byte> GenderNo { get; set; }
public Nullable<int> mPhone { get; set; }
public Nullable<long> mMobile { get; set; }
public Nullable<int> mEmrgPhone { get; set; }
public Nullable<long> mEmrgMobile { get; set; }
public string mEmail { get; set; }
public string mProfilePicExt { get; set; }
public bool mIsOperator { get; set; }
public bool mIsAdmin { get; set; }
public virtual ...
}
namespace Project.Model.membership
//my class handling data annotations, not work!
[MetadataType(typeof(Member_Validation))]
public partial class Member
{
}
//buddy class
[Bind(Exclude = "mId")]
public sealed class Member_Validation
{
//public System.Guid mId { get; set; }
public byte MemberTypeNo { get; set; }
[Required(ErrorMessage = "blah blah")]
public string mName { get; set; }
[Required]
public string mLName { get; set; }
public string mUserName { get; set; }
public string mPass { get; set; }
public Nullable<byte> MarriageStatusNo { get; set; }
public Nullable<byte> GenderNo { get; set; }
public Nullable<int> mPhone { get; set; }
public Nullable<long> mMobile { get; set; }
public Nullable<int> mEmrgPhone { get; set; }
public Nullable<long> mEmrgMobile { get; set; }
public string mEmail { get; set; }
public string mProfilePicExt { get; set; }
public bool mIsOperator { get; set; }
public bool mIsAdmin { get; set; }
}
ok, so firstly, take a look on this: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model
Secondly, I would recommend to use ViewModels to validate objects. Like in code below (in shortcut):
MemberViewModel.cs
And then, send your ViewModel to Edit/Add view:
Add.cshtml
Controler and Add ActionResult
With this approach, you have clear Entity model (
POCO
classes likeMember
) and Domian models (ViewModels
like MemberViewModel) with custom validation.