如何为部分类添加数据注释? [英] How to add data annotations to partial class?

查看:88
本文介绍了如何为部分类添加数据注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自动生成的类,上面有一个属性。我想在同一类型的另一个局部类中向该属性添加一些数据注释。我该怎么办?

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.

推荐答案

就像我用 MetadataTypeAttribute找出了一种类似于上面链接的不同方式

namespace MyApp.BusinessObjects
{
    [MetadataTypeAttribute(typeof(SomeClass.Metadata))]{
    public partial class SomeClass
    {
        internal sealed class Metadata
        {
            private Metadata()
            {
            }

            [Required]
            public string Name{ get; set; }
        }
    }
}

这篇关于如何为部分类添加数据注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆