伙伴类仅适用于数据注释吗?
伙伴类仅适用于数据注释或任何属性吗?我一直在尝试将 ColumnAttribute 附加到我的好友类中的字段,但它似乎没有在原始类中得到处理。这两个类通过 MetadataType 链接。
Do buddy classes only work for dataannotations, or for any attribute? I've been trying to attach a ColumnAttribute to a field in my buddy class, but it appears that it doesn't get processed in the original class. The two classes are linked via MetadataType.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的答案不是特定于 DataAnnotations 的,这是关于如何关联类型描述符的全局答案。
创建
TypeDescriptionProvider
描述类的关系(在某些情况下,您可以跳过这部分,您可以使用现有的描述符,例如AssociatedMetadataTypeTypeDescriptionProvider
)。然后使用
TypeDescriptor.AddProvider
或TypeDescriptor.AddProviderTransparent< /code>
动态附加它们运行时。
我的建议是拥有一个包含标记类型列表的服务,并通过它运行所有类型(按需,因此性能成本在应用程序运行时分散),并且在处理类型时,将该类型添加到列表,下次请求此类型时,您就知道它在列表中。
My answer is not DataAnnotations specific, this is a globabl answer of how to associate type descriptors.
Create a subclass of
TypeDescriptionProvider
that describes the relation of the classes (you can skip this part in some cases where u can use an existing descriptor such asAssociatedMetadataTypeTypeDescriptionProvider
).Then use
TypeDescriptor.AddProvider
orTypeDescriptor.AddProviderTransparent
to dynamically attach them runtime.My suggestion is have a service that has a list of flagged types, and run all the types thru it (on demand, so the performance cost is spread at the application running time), and when a type is processed, add the type to the list, and next time this type requests, you know it's in the list.
伙伴类技术对于 DataAnnotations 来说并没有什么特别之处。但是,只有当您使用的反射代码对
MetadataType
属性执行某些操作时,它才有效。因此,ASP.NET MVC 是处理伙伴类概念的代码库示例,而 Linq-to-sql 则不然。因此,目前如果您想使用好友类来添加 ColumnAttribute,您就会陷入困境。然而,如果您确实需要变得更奇特,Linq-to-SQL 将采用带有映射的 XML 文档,而不是使用属性。您可以使用它来构建映射,作为您可能使用伙伴类的实例的替代方案。如果您需要变得非常非常奇特,请继续创建您的伙伴类,然后针对您的 Linq 属性修饰类编写您自己的伙伴类感知反射处理程序,并根据您的 DataContext 需求构造 XML 映射文档。您可能可以用不到 50 行代码来完成此操作。
The buddy class technique is not anything special to DataAnnotations. However, it only works if the reflection code you're using does something with the
MetadataType
attribute. So, ASP.NET MVC is an example of a codebase that handles the buddy class concept, while Linq-to-sql does not. So, at the moment you're stuck if you want to use buddy classes to add aColumnAttribute
. However, if you really need to get fancy, Linq-to-SQL will take an XML document with the mappings instead of using attributes. You could use that to build your mappings as an alternative for the instances where you might have used a buddy class.If you need to get really, really fancy, go ahead and make your buddy class and then write your own buddy-class-aware reflection handler against your Linq attribute decorated classes and construct XML mapping documents from that for your DataContext needs. You could probably do that in under 50 lines of code.