I have an auto generated class with a property on it. I want to add some data annotations to that property in another partial class of the same type. How would I do that?
我有一个自动生成的类,上面有一个属性。我想在另一个相同类型的部分类中向该属性添加一些数据注释。我该怎么办?
namespace MyApp.BusinessObjects
{
[DataContract(IsReference = true)]
public partial class SomeClass: IObjectWithChangeTracker, INotifyPropertyChanged
{
[DataMember]
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
private string _name;
}
}
and in another file I have:
在另一个文件中我有:
namespace MyApp.BusinessObjects
{
public partial class SomeClass
{
private SomeClass()
{
}
[Required]
public string Name{ get; set; }
}
}
Currently, I get an error stating that the name property already exists.
目前,我收到一条错误,指出name属性已存在。
2 个解决方案
#1
17
Looks like I figured out a different way similar to the link above using MetadataTypeAttribute
:
看起来我使用MetadataTypeAttribute找出了与上面的链接类似的不同方式:
namespace MyApp.BusinessObjects
{
[MetadataTypeAttribute(typeof(SomeClass.Metadata))]{
public partial class SomeClass
{
internal sealed class Metadata
{
private Metadata()
{
}
[Required]
public string Name{ get; set; }
}
}
}
#2
1
I'm using the below to also support multiple foreign keys in the same table that refer to the same table. Example, the person has two parents (Father and Mother) who are both Person class.
我使用下面的内容也支持同一个表中引用同一个表的多个外键。例如,该人有两个父母(父亲和母亲),他们都是人类。
[MetadataTypeAttribute(typeof(SomeClassCustomMetaData))]
public partial class SomeClass
{
}
public class SomeClassCustomMetaData
{
[Required]
public string Name { get; set; }
[InverseProperty("Father")]
public virtual Parent ParentClass { get; set; }
[InverseProperty("Mother")]
public virtual Parent ParentClass1 { get; set; }
}
#1
17
Looks like I figured out a different way similar to the link above using MetadataTypeAttribute
:
看起来我使用MetadataTypeAttribute找出了与上面的链接类似的不同方式:
namespace MyApp.BusinessObjects
{
[MetadataTypeAttribute(typeof(SomeClass.Metadata))]{
public partial class SomeClass
{
internal sealed class Metadata
{
private Metadata()
{
}
[Required]
public string Name{ get; set; }
}
}
}
#2
1
I'm using the below to also support multiple foreign keys in the same table that refer to the same table. Example, the person has two parents (Father and Mother) who are both Person class.
我使用下面的内容也支持同一个表中引用同一个表的多个外键。例如,该人有两个父母(父亲和母亲),他们都是人类。
[MetadataTypeAttribute(typeof(SomeClassCustomMetaData))]
public partial class SomeClass
{
}
public class SomeClassCustomMetaData
{
[Required]
public string Name { get; set; }
[InverseProperty("Father")]
public virtual Parent ParentClass { get; set; }
[InverseProperty("Mother")]
public virtual Parent ParentClass1 { get; set; }
}