15

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.

O.O
  • 11,077
  • 18
  • 94
  • 182
  • I would be surprised if this is possible - you're best bet is changing how the class is autogenerated to allow annotations to be specified there. – Will A May 25 '11 at 22:35
  • 1
    Possible duplicate of http://stackoverflow.com/questions/1232497/adding-dataannontations-to-generated-partial-classes – Reddog May 25 '11 at 22:40
  • @Will - Ya, the error I'm getting suggests it isn't possible, hopefully there is a better way than changing the auto-gen code. – O.O May 25 '11 at 22:42

2 Answers2

17

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; }
        }
    }
}
O.O
  • 11,077
  • 18
  • 94
  • 182
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; }
}
JeeShen Lee
  • 3,476
  • 5
  • 39
  • 59