使用 EF 进行数据注释

发布于 2024-10-31 03:49:56 字数 684 浏览 0 评论 0原文

我已经按照 这里,但它对我不起作用。

我有一个具有以下结构的表,

Table - Category
    id int (pk not null)
    CategoryName varchar(100) (null)

我已经创建了 edmx 文件等。

我创建了 Category.cs 文件,如下所示。

[MetadataType(typeof(CategoryMetaData))]
public partial class Category
{
}

public class CategoryMetaData
{
    [Required(ErrorMessage = "Category Name is required.")]
    public object CategoryName;
}

但我的验证不起作用。

有什么我错过的吗?

I have tried DataAnnotation as described here, but it does not work for me.

I have a table with the following structure

Table - Category
    id int (pk not null)
    CategoryName varchar(100) (null)

I already created my edmx file and all.

I have created the Category.cs file also like below.

[MetadataType(typeof(CategoryMetaData))]
public partial class Category
{
}

public class CategoryMetaData
{
    [Required(ErrorMessage = "Category Name is required.")]
    public object CategoryName;
}

But my validations are not working.

Is there anything I've missed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

贱人配狗天长地久 2024-11-07 03:49:56

我发现 ObjectContext 不适用于 DataAnnotations。您必须切换到使用 DbContext,然后它才能起作用。下载 EF 4.x DbContext T4 文件并在您的模型上尝试。不知道为什么会这样,希望有专家指点一下。

I have found that ObjectContext does not work with DataAnnotations. You have to switch to using DbContext, then it works. Download the EF 4.x DbContext T4 file and try it on your model. Not sure why this is true, was hoping an expert would chime in.

久而酒知 2024-11-07 03:49:56

UPD
解决方案在这里。

验证之前,需要手动注册元数据类

==================

我想这个问题与EF为您的实体生成的代理类有关。您可以在运行时轻松检查这一点:只需查看 GetType().FullName。

如果属性被标记为不可继承,则它不会应用于继承的类中。并且代理类是从实体类派生的,所以不可继承的属性就丢失了。

我试图通过手动检查属性来在 WebForms 项目中使用 DataAnnotations。但两者都

System.ComponentModel.DataAnnotations.Validator.TryValidateObject(entity, new ValidationContext(value, null, null), results, true);

不起作用

PropertyInfo[] properties = value.GetType()
                 .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

var validationProperties = properties.Select(prop => new
        {
            Property = prop,
            ValidationAttributes = Attribute.GetCustomAttributes(prop, typeof(ValidationAttribute), true)
        }).Where(valProp => valProp.ValidationAttributes.Any());


我已经使用与 EF 无关的简单类尝试了这些代码,并且所有 DataAnnotations 属性均已找到并正确检查。

[MetadataType(typeof(TestValidObject_Metadata))]
public class TestValidObject
{
    public string IdName { get; set; }
}

public class TestValidObject_Metadata
{
    [Required, DisplayName("Id name")]
    public object IdName { get; set; }
}

requiredAttribute 的定义是

[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter, AllowMultiple = false)]
public class RequiredAttribute : ValidationAttribute

并且默认情况下它成为可继承的属性。而且我不知道为什么

Attribute.GetCustomAttributes(prop, typeof(ValidationAttribute), true)  
// true specifies to also search the ancestors of element for custom attributes.

没有抓住它。

欢迎任何想法。

UPD
Solution here.

Before validating, you need to manually register the metadata class

==================

I suppose this problem is related to proxy classes, which EF generates for your entities. You can check this easily in runtime: just see GetType().FullName.

If attribute is marked as non-inheritable, it won't be applied in inherited class. And proxy classes derive from entity classes, so non-inheritable attributes are lost.

I'm trying to use DataAnnotations in WebForms project by checking attributes by hand. But neither

System.ComponentModel.DataAnnotations.Validator.TryValidateObject(entity, new ValidationContext(value, null, null), results, true);

nor

PropertyInfo[] properties = value.GetType()
                 .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

var validationProperties = properties.Select(prop => new
        {
            Property = prop,
            ValidationAttributes = Attribute.GetCustomAttributes(prop, typeof(ValidationAttribute), true)
        }).Where(valProp => valProp.ValidationAttributes.Any());

doesn't work.
I've tried these code with simple class not related to EF, and all DataAnnotations attributes were found and checked correctly.

[MetadataType(typeof(TestValidObject_Metadata))]
public class TestValidObject
{
    public string IdName { get; set; }
}

public class TestValidObject_Metadata
{
    [Required, DisplayName("Id name")]
    public object IdName { get; set; }
}

RequiredAttribute's definition is

[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter, AllowMultiple = false)]
public class RequiredAttribute : ValidationAttribute

and by default it becomes inheritable attribute. And I don't know why

Attribute.GetCustomAttributes(prop, typeof(ValidationAttribute), true)  
// true specifies to also search the ancestors of element for custom attributes.

doesn't catch it.

Any ideas are welcome.

っ左 2024-11-07 03:49:56

CateogryMetaData 中的 CategoryName 应该是一个属性,并且与原始属性具有相同的类型。试试这个:

public class CategoryMetaData
{
    [Required(ErrorMessage = "Category Name is required.")]
    public string CategoryName {get;set;}
}

CategoryName in CateogryMetaData should be a property and has the same type as the original property. Try this:

public class CategoryMetaData
{
    [Required(ErrorMessage = "Category Name is required.")]
    public string CategoryName {get;set;}
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文