【问题标题】:MinLength constraint on ICollection fails, Entity FrameworkICollection 上的 MinLength 约束失败,实体框架
【发布时间】:2012-07-19 17:33:53
【问题描述】:

这是我拥有的数据模型:

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

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

我的问题是,当我稍后尝试创建一个新团队(只有一个用户)时,在保存上下文时会遇到以下问题。

调用 System.ComponentModel.DataAnnotations.MinLengthAttribute.IsValid 时,在验证“用户”期间引发意外异常。有关详细信息,请参阅内部异常。

内部异常如下:

{“无法将'System.Collections.Generic.List`1[MyNameSpace.Model.User]'类型的对象转换为'System.Array'类型。”}

这是实际保存的代码(目前在控制器中):

        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");
        }

那么,这里发生了什么?是我做错了什么,还是发生了其他事情?

【问题讨论】:

    标签: casting asp.net-mvc-4 entity-framework-4.3 icollection


    【解决方案1】:

    我不相信您将能够使用 MinLength 属性来实现您想要实现的目标。 Here 是 MinLength 属性的 msdn 页面。根据描述:“指定属性中允许的 string 数据数组的最小长度。” 如您所见,它只能用于字符串数据数组.您可能需要创建自己的自定义 ValidationAttribute 来处理您的场景。

    【讨论】:

    • 您的答案似乎是正确的,但您错误地引用了 MSDN 页面。它显示:“指定属性中允许的数组或字符串数​​据的最小长度。” (或,不属于)。不幸的是,他们选择不让它支持收藏。这似乎是一个显而易见的选择,但是哦,好吧......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    相关资源
    最近更新 更多