[英]C# Object Model from XSD with Additional Property Attributes
I'm using Microsoft's excellent XSD.exe tool to build a C# object model from my XSD schema. I'm using Microsoft's excellent XSD.exe tool to build a C# object model from my XSD schema.
I would like to add additional C# attributes to the resulting C# file auto-generated by XSD object model (to define Validation behavior for Razor but maybe for other things too). I would like to add additional C# attributes to the resulting C# file auto-generated by XSD object model (to define Validation behavior for Razor but maybe for other things too).
For example, in my XSD I have something like the following:例如,在我的 XSD 中,我有如下内容:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="MyThing">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" name="SomeThings">
<xs:complexType>
<xs:attribute name="Email" type="xs:string" use="required" />
The XSD tool will output a C# class with (amongst other things) a property such as this: XSD 工具将 output 和 C# class 和其他属性:
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Email {
get {
return this.emailField;
}
set {
this.emailField = value;
}
}
I am wondering what might be the best way to add additional C# property attributes such as我想知道添加其他 C# 属性属性的最佳方法是什么,例如
[Required]
[EmailAddress]
So the final C# would be:所以最终的 C# 将是:
/// <remarks/>
[Required]
[EmailAddress]
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Email {
get {
return this.emailField;
}
set {
this.emailField = value;
}
}
Can this be done with the XSD.exe tool (I couldn't find a way)?这可以用 XSD.exe 工具完成吗(我找不到方法)? Or is there a way to add property attributes at runtime (is that a good idea)?或者有没有办法在运行时添加属性属性(这是个好主意)?
The ideal would be able to add this info the XSD, eg理想的情况是能够将此信息添加到 XSD,例如
<xs:attribute name="Email" someUnknownNamespace:customCSharpAttributes="Required,EmailAddress" type="xs:string" use="required" />
This cannot be done with the XSD.exe tool - ostensibly, it has no idea what an EmailAddress
is, given that the field is given the type of xs:string
.使用 XSD.exe 工具无法做到这一点 - 从表面上看,它不知道EmailAddress
是什么,因为该字段的类型是xs:string
。
However, you mention Razor and this makes me think of the System.ComponentModel.DataAnnotations namespace.但是,您提到了 Razor,这让我想到了 System.ComponentModel.DataAnnotations 命名空间。 It has the given [Required]
attribute and a lot more, including one that does email address annotations.它具有给定的[Required]
属性和更多属性,包括执行 email 地址注释的属性。
As far as automatically annotating the data - the XML schema you provided is insufficient to automatically be annotated with the tools in that namespace.至于自动注释数据 - 您提供的 XML 模式不足以使用该命名空间中的工具自动注释。
There are open source solutions which do what you describe (given an adequate schema).有一些开源解决方案可以按照您的描述进行(给定足够的模式)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.