1
votes

I recently just learned about putting your data annotations in a new partial class so that they persist on edmx updates from the database.
Database-first approach and modifying the database schema
Update Model From Database (Database First)

In one of my models I have two attributes: firstName and lastName. I had created a virtual property for full name seen below.

public virtual string fullName { get {return firstName + " " + lastName; } }

The fullName property works when it's in the edmx generated .tt model class, but when I put it in my "buddy" partial class that hold my annotations, it doesn't work (ie isn't recognized by the rest of the app as an attribute of my class).

How do I get a aggregate virtual property like the fullName property above that won't be overwritten by a database update to the edmx?

1

1 Answers

1
votes

I figured it out. The accompanying partial class for data annotations has a classMetaData class that you use to set the Meta Data for your partial class (ie your annotations go here). The aggregate attribute has to go in the partial class though (not the Meta Data class).

So the second partial class code should look something like this:

namespace MyProject.Models
{
[MetadataType(typeof(PersonMetaData))]
public partial class Person
{
    //this is where you put new aggregate properties
    public virtual string fullName { get { return firstName + " " + lastName; } }
}

public class PersonMetaData
{
    //this is where you put data annotations
    [Required]
    public string firstName { get; set; }
    [Required]
    public string lastName { get; set; }
} 

}