gpt4 book ai didi

casting - ICollection 上的 MinLength 约束失败, Entity Framework

转载 作者:行者123 更新时间:2023-12-02 03:42:54 26 4
gpt4 key购买 nike

这是我的数据模型:

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

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

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

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

内部异常如下:

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

这是实际保存的代码(目前位于 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");
}

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

最佳答案

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

关于casting - ICollection 上的 MinLength 约束失败, Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11566265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com