DataAnnotations with EntityFramework (Database First) Method

I have a project in which I have a database model class that comes with a separate EDMX EF model. In the same solution, I have a web service that accesses this project along with the model class. I want the model class to annotate data to the front end for validation, but does not receive any confirmation at all.

For brevity, the model class (in my model project) is as follows. My web service references this class and is used as an interface.

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ServiceModel; using System.Runtime.Serialization; [DataContract] [MetadataType(typeof(CustomerMetaData))] public partial class Customer { } public class CustomerMetaData { [DataMember] public object CustomerID { get; set; } [Required] [StringLength(50)] [DataType(DataType.EmailAddress)] [DataMember] public object Email { get; set; } } 

When I click the "Submit" button on the form, it tries to add an entry and does not do any verification. An error occurred at runtime informing me that an email address is required. I obviously want this check to be done with data annotations.

How can i do this?

An actual runtime error is returned saying that the email address should not be NULL when an entry tries to be added. It's right. The database column requires a value.

I thought that having data annotations in the model, if something is wrong with the interface and the model is not valid after the form tries to be submitted, the corresponding data annotation error should be displayed on the form. I got the impression that there is no need to write any specific check on the client side. The model should take care of this for you. Am I wrong in this assumption?

There are articles on the Internet on how to do this using CodeFirst , but I have seen none how to do this using DataBaseFirst . How can I do that?

Once again, my Customer class is as follows.

 using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ServiceModel; using System.Runtime.Serialization; namespace YeagerTechModel { [Serializable] [DataContract] //[MetadataType(typeof(CustomerMetaData))] public partial class Customer { public Customer() { this.Projects = new HashSet<Project>(); } [DataMember] public short CustomerID { get; set; } [Required] [StringLength(50)] [DataType(DataType.EmailAddress)] [DataMember] public string Email { get; set; } [StringLength(50)] [DataType(DataType.Text)] [DataMember] public string Company { get; set; } [StringLength(50)] [DataType(DataType.Text)] [DataMember] public string FirstName { get; set; } [StringLength(50)] [DataType(DataType.Text)] [DataMember] public string LastName { get; set; } [StringLength(50)] [DataType(DataType.Text)] [DataMember] public string Address1 { get; set; } [StringLength(50)] [DataType(DataType.Text)] [DataMember] public string Address2 { get; set; } [StringLength(50)] [DataType(DataType.Text)] [DataMember] public string City { get; set; } [StringLength(2)] [DataType(DataType.Text)] [DataMember] public string State { get; set; } [StringLength(10)] [DataType(DataType.Text)] [RegularExpression(@"^\d{5}(-\d{4})?$")] [DataMember] public string Zip { get; set; } [StringLength(12)] [DataType(DataType.PhoneNumber)] [DataMember] public string HomePhone { get; set; } [StringLength(12)] [DataType(DataType.PhoneNumber)] [DataMember] public string CellPhone { get; set; } [StringLength(100)] [DataType(DataType.Url)] [DataMember] public string Website { get; set; } [StringLength(50)] [DataType(DataType.EmailAddress)] [DataMember] public string IMAddress { get; set; } [DataMember] public System.DateTime CreatedDate { get; set; } [DataMember] public Nullable<System.DateTime> UpdatedDate { get; set; } public virtual ICollection<Project> Projects { get; set; } } } 

When I debug "if (ModelState.IsValid)" in my client, the property always returns true. As if DataAnnotations are not even recognized. When debugging, I check the ModelState object and it has all the property values โ€‹โ€‹(an empty string in all cases, since I'm trying to cause an error). I should get an isRequired error to the email address that I intentionally left blank.

 [HttpPost] public ActionResult Create(YeagerTechWcfService.Customer cust) { if (ModelState.IsValid) { try { db.AddCustomer(cust); TempData["ErrCode"] = "Customer successfully added."; return RedirectToAction("Index", "Home"); } catch (Exception ex) { ViewData["ErrCode"] = "CustErr"; ViewBag.Error = ex.Message; return View(); } } else return View(); } 
+4
source share
2 answers

Unfortunately, this annotation only affects rendering, not validation. I had the same problem with DataType.Url and it was also discussed in the question Is DataTypeAttribute validation in MVC2? (although for MVC 2 - but the problem seems the same in 3).

Just uncheck the regexp data on it:

 [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Email was invalid.")] 
+1
source

To slightly increase this, in MVC 3 you can go one more route to use validation. First, I use the MVC 3 + EF database, and I can use this code in the extension / partial model class:

 [MetadataType(typeof(Foobar.Metadata))] [Serializable] public partial class Foobar { private sealed class Metadata { [Required] [MinLength(10)] public object Name { get; set; } } // Other stuff here } 

Then, when I can feed my little Foobar with an invalid name in the controller action, and I can get validation errors correctly using TryValidateModel instead of ModelState.IsValid (Horror of horrors, I am not bound to data).

  Foobar c = new Foobar(); c.Name = "ponies"; var y = TryValidateModel(c); if (!y) { foreach (var item in ModelState.Values) { foreach (var err in item.Errors) { DoxLog.Error(err.ErrorMessage, err.Exception); } } } 
0
source

All Articles