locked
Validation failed for one or more entities. :) RRS feed

  • Question

  • User-81166443 posted

    Hey Guys :) Tried to do some google'ing but havnt helped yet.

    I've made a entity datamodel generated from my database. Afterwards added a controler bound to it.

    A simple create function gives me "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."

    The method 

      [HttpPost]
            public ActionResult Create(ResturantSet resturantset)
            {
                if (ModelState.IsValid)
                {
                    db.ResturantSet.Add(resturantset);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                return View(resturantset);
            }


    This is already added
    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")




     How can i fire the validation? :) 

    Friday, January 25, 2013 5:52 PM

Answers

  • User-642706772 posted

    Please try adding some validation attributes to your ReataurantSet.cs class

     public partial class ResturantSet
        {
            public ResturantSet()
            {
                this.MenuSet = new HashSet<MenuSet>();
            }
        
            public int Id { get; set; }
    
            [Required]
            public string Navn { get; set; }
    
            [Required]
            [MaxLength(255)]
            public string Kontaktperson { get; set; }
    
            public string Lokation { get; set; }
            public string Info { get; set; }
            public string SoegeThumbnail { get; set; }
            public string ResturantBillede { get; set; }
        
            public virtual ICollection<MenuSet> MenuSet { get; set; }
        }

    The validation attriubutes are in the System.ComponentModel.DataAnnotations namespace, so make sure to include it in your model.

    After you do this, the model validator should be able to figure out how to validate your objects, and ModelState.IsValid should work properly. This works for code-first, so I'm not 100% sure if it will work for you, but give it a try.

    Here is an article on using data annotations in your models.

    http://blogs.msdn.com/b/efdesign/archive/2010/03/30/data-annotations-in-the-entity-framework-and-code-first.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 26, 2013 3:30 PM

All replies

  • User-642706772 posted

    You can use a try/catch block to inspect the entity validation errors:

    [HttpPost]
    public ActionResult Create(ResturantSet resturantset)
    {
        if (ModelState.IsValid)
        {
            try
            {
    	        db.ResturantSet.Add(resturantset);
    	        db.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
    		    foreach (var validationErrors in dbEx.EntityValidationErrors)
    		    {
    		        foreach (var validationError in validationErrors.ValidationErrors)
    		        {
    		            System.Console.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
    		        }
    		    }
            }
    
            return RedirectToAction("Index");
        }
    
        return View(resturantset);
    }


    Note: dbEntityValidationException is in the System.Data.Entity.Validation namespace

    Saturday, January 26, 2013 2:30 AM
  • User-81166443 posted

    I would like them to happen on the client-side via. jQuery, any possible solution ? 

    Saturday, January 26, 2013 5:55 AM
  • User1266497125 posted

    You can always package the result and return JsonResult. The previous answer can be used for something like this:

    [HttpPost] 
    public ActionResult Create(ResturantSet resturantset) 
    { 
        if (ModelState.IsValid) 
        { 
            try 
            { 
                    db.ResturantSet.Add(resturantset); 
                    db.SaveChanges(); 
            } 
            catch (DbEntityValidationException dbEx) 
            { 
                  var errorList = new List<string>();
    
                        foreach (var validationErrors in dbEx.EntityValidationErrors) 
                        { 
                            foreach (var validationError in validationErrors.ValidationErrors) 
                            {
                                errorList.Add(String.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage)); 
                            } 
                        } 
                  return Json(errorList);
            } 
     
            return RedirectToAction("Index"); 
        } 
     
        return View(resturantset); 
    }

    Then inside you jQuery code use $.each() method to process the string. Also, please notice that I did not test this code, but I just want to give you an idea how to get it done. Also, the above will work if you POSTed the request through one of jQuery's Ajax methods like $.ajax or $.post.

    Saturday, January 26, 2013 8:36 AM
  • User-642706772 posted

    I think we are moving backwards here...

    The validation should occur during model binding, and is saved in the ModelState. When you check if ModelState.IsValid, it should know whether there will be any entity validation errors. If this is working, the client-side validation should "just work"

    How are you defining your validation rules? Can we see your RestaurantSet model?

    Saturday, January 26, 2013 11:48 AM
  • User-81166443 posted

    First thx for all the answers guys! :)

    This is the ResturantSet

    CREATE TABLE [dbo].[ResturantSet](
    	[Id] [int] IDENTITY(1,1) NOT NULL,
    	[Navn] [nvarchar](max) NOT NULL,
    	[Kontaktperson] [nvarchar](max) NOT NULL,
    	[Lokation] [nvarchar](max) NOT NULL,
    	[Info] [nvarchar](max) NOT NULL,
    	[SoegeThumbnail] [nvarchar](max) NOT NULL,
    	[ResturantBillede] [nvarchar](max) NOT NULL,
     CONSTRAINT [PK_ResturantSet] PRIMARY KEY CLUSTERED 
    (
    	[Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
    )



    The SQL which creates it. :) The Model is made straight from it without any changes. 
     

    Saturday, January 26, 2013 1:29 PM
  • User1558965567 posted
    You should be using a seperate view model for your views with data annotations.
     
    public class MyViewModel {
       [Required]
       public string FirstName {get;set;}
    
       [Required]
       public string LastName {get;set;}
    
       ... etc.
    }
    

    Saturday, January 26, 2013 1:45 PM
  • User-642706772 posted

    I've only ever used the code-first approad for the Entity Framework.

    Does your project generate a model class (RestaurantSet.cs) from that table? If so, can you post that code?

    Saturday, January 26, 2013 1:48 PM
  • User-81166443 posted

    This is the ResturantSet.Cs it made for me 

     public partial class ResturantSet
        {
            public ResturantSet()
            {
                this.MenuSet = new HashSet<MenuSet>();
            }
        
            public int Id { get; set; }
            public string Navn { get; set; }
            public string Kontaktperson { get; set; }
            public string Lokation { get; set; }
            public string Info { get; set; }
            public string SoegeThumbnail { get; set; }
            public string ResturantBillede { get; set; }
        
            public virtual ICollection<MenuSet> MenuSet { get; set; }
        }
    


     

    Saturday, January 26, 2013 2:39 PM
  • User-642706772 posted

    Please try adding some validation attributes to your ReataurantSet.cs class

     public partial class ResturantSet
        {
            public ResturantSet()
            {
                this.MenuSet = new HashSet<MenuSet>();
            }
        
            public int Id { get; set; }
    
            [Required]
            public string Navn { get; set; }
    
            [Required]
            [MaxLength(255)]
            public string Kontaktperson { get; set; }
    
            public string Lokation { get; set; }
            public string Info { get; set; }
            public string SoegeThumbnail { get; set; }
            public string ResturantBillede { get; set; }
        
            public virtual ICollection<MenuSet> MenuSet { get; set; }
        }

    The validation attriubutes are in the System.ComponentModel.DataAnnotations namespace, so make sure to include it in your model.

    After you do this, the model validator should be able to figure out how to validate your objects, and ModelState.IsValid should work properly. This works for code-first, so I'm not 100% sure if it will work for you, but give it a try.

    Here is an article on using data annotations in your models.

    http://blogs.msdn.com/b/efdesign/archive/2010/03/30/data-annotations-in-the-entity-framework-and-code-first.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 26, 2013 3:30 PM
  • User-81166443 posted

    Thx everyone! :) And thx mgasparel for the helping answer :) 

    Sunday, January 27, 2013 12:50 PM