使用 EF 进行数据注释
我已经按照 这里,但它对我不起作用。
我有一个具有以下结构的表,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现 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.
UPD
解决方案在这里。
==================
我想这个问题与EF为您的实体生成的代理类有关。您可以在运行时轻松检查这一点:只需查看 GetType().FullName。
如果属性被标记为不可继承,则它不会应用于继承的类中。并且代理类是从实体类派生的,所以不可继承的属性就丢失了。
我试图通过手动检查属性来在 WebForms 项目中使用 DataAnnotations。但两者都
不起作用
。
我已经使用与 EF 无关的简单类尝试了这些代码,并且所有 DataAnnotations 属性均已找到并正确检查。
requiredAttribute 的定义是
并且默认情况下它成为可继承的属性。而且我不知道为什么
没有抓住它。
欢迎任何想法。
UPD
Solution here.
==================
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
nor
doesn't work.
I've tried these code with simple class not related to EF, and all DataAnnotations attributes were found and checked correctly.
RequiredAttribute's definition is
and by default it becomes inheritable attribute. And I don't know why
doesn't catch it.
Any ideas are welcome.
CateogryMetaData 中的 CategoryName 应该是一个属性,并且与原始属性具有相同的类型。试试这个:
CategoryName in CateogryMetaData should be a property and has the same type as the original property. Try this: