Question

This is the datamodel I have:

public class Team
{
    [Key]
    public int Id { get; set;} 
    [Required]
    public string Name { get; set; }

    [MinLength(1)]
    public virtual ICollection<User> Users { get; set; }
}

My issue is that when I later try to create a new Team (that has one user) I get the following issue when the context is saving.

An unexpected exception was thrown during validation of 'Users' when invoking System.ComponentModel.DataAnnotations.MinLengthAttribute.IsValid. See the inner exception for details.

The inner exception is the following:

{"Unable to cast object of type 'System.Collections.Generic.List`1[MyNameSpace.Model.User]' to type 'System.Array'."}

Here is the code for the actual saving (which for now is in the controller):

        if (ModelState.IsValid)
        {
            team.Users = new List<User>();
            team.Users.Add(CurrentUser);//CurrentUser is a property that gives me the currently active User (MyNamespace.Model.User).
            DB.Teams.Add(team);//DB is a DbContext object that holds DbSets of all my models
            DB.SaveChanges();
            return RedirectToAction("Index");
        }

So, what's going on here? Am I doing something wrong, or is there something else happening?

Was it helpful?

Solution

I do not believe that you will be able to use the MinLength Attribute for what you are trying to achieve. Here is the msdn page for the MinLength Attribute. Based on the description: "Specifies the minimum length of array of string data allowed in a property." So as you can see it can only be used against arrays of string data. You may need to create your own custom ValidationAttribute to handle your scenario.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top