Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data annotations to partial class?

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.

like image 735
O.O Avatar asked May 25 '11 22:05

O.O


People also ask

Can we override partial class in C#?

Ordinarily, this means that you cannot override them; you cannot override in one partial class the methods that are defined in another partial definition of the same class. Nevertheless, you can override these methods by setting the Generates Double Derived flag for the domain class.

Can a partial class implement an interface?

Partial class, interface and structure was introduced in C# 2.0. Now it is possible to split the definition of an class, interface and structure over more than one source files. Moreover the other parts of the class, struct, or interface should be defined in the same namespace or assembly.

Can we create object of partial class?

All parts of a partial class should be in the same namespace. Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files of a different class library project. Each part of a partial class has the same accessibility.


1 Answers

Looks like I figured out a different way similar to the link above using MetadataTypeAttribute:

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

            [Required]
            public string Name{ get; set; }
        }
    }
}
like image 61
O.O Avatar answered Oct 23 '22 06:10

O.O