.net core Fluent API的自定义数据注释
对于我的ef核心应用程序,我创建了一些受.net core Fluent API的自定义数据注释,.net-core,data-annotations,ef-fluent-api,ef-core-2.1,.net Core,Data Annotations,Ef Fluent Api,Ef Core 2.1,对于我的ef核心应用程序,我创建了一些受DataAnnotations约束的类。我E我必须定义一个自定义属性,以确保IList中至少有一项 自定义ValidationAttribute: public class ListLengthAttribute : ValidationAttribute { public int Min { get; set; } public int Max { get; set; } public ListLengthAttribute()
DataAnnotations
约束的类。我E我必须定义一个自定义属性,以确保IList
中至少有一项
自定义ValidationAttribute
:
public class ListLengthAttribute : ValidationAttribute
{
public int Min { get; set; }
public int Max { get; set; }
public ListLengthAttribute()
{
Min = 0;
Max = int.MaxValue;
}
public override bool IsValid(object value)
{
IList listValue = value as IList;
if (listValue != null)
{
int listLength = listValue.Count;
return listLength >= Min && listLength <= Max;
}
return false;
}
}
您主要需要了解其中每一项的目的。数据注释用于定义模型的规则和约束。这些可用于服务器端、客户端和数据库验证(用于相关部分)。自定义的
ValidationAttribute
可用于服务器端验证
Fluent API纯粹用于转换为数据库配置。只有诸如MaxLength(n)
等属性在客户端、服务器端和数据库端具有直接含义(varchar(n)
)。因此,这些属性在fluentapi中确实有直接的替代项。但是,EF不会自动理解自定义验证在数据库中的含义。例如,在您的案例中,当max length为1时,验证似乎转换为一对一关系。因此,对于这个感知示例,您可以在fluentapi中设置一对一。在这种情况下,EF无法检查代码并理解验证的意图
对于“最大长度”和“最小长度”的所有其他值,没有可以在数据库中设置的映射配置。因此,fluent API不能为其提供映射功能。如果您使用的数据库确实具有类似的功能,则可以查看其EF库的文档以了解映射功能
基于您希望远离数据注释的原因,您真正想要的可能是流畅的验证。您可以查看这个库,它在使用这个库时提供了一个干净的模型实现示例
public class Dummy
{
[ListLength( Min = 1, ErrorMessage = "Each dummy should contain at least 1 foo." )]
public List<Foo> Foos { get; set; }
}