Entity Framework Entity Property Override

asp.net-mvc-3 c# entity-framework overriding

Question

I have an entity in EF named Profile and I would like to add data annotation attributes to the FirstName property of this entity. So, I created a new partial class like so;

public partial class Profile : EntityObject
{
    [Required]
    [Display(Name = "First Name")]
    [EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]
    [DataMemberAttribute()]
    override public global::System.String FirstName
    {
        get
        {
            return _FirstName;
        }
        set
        {
            OnFirstNameChanging(value);
            ReportPropertyChanging("FirstName");
            _FirstName = StructuralObject.SetValidValue(value, false);
            ReportPropertyChanged("FirstName");
            OnFirstNameChanged();
        }
    }
}

But I am getting this;

The type 'CC.Models.Profile' already contains a definition for 'FirstName'

Any ideas?

Regards,
Ryan

1
5
7/8/2019 4:36:50 PM

Accepted Answer

You unfortunately can't change it like that. You have to create a metadata class and add the metadata attributes to that class. See below link:

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute.aspx

Have a look at this link to see some issues with generating a metadata class, what I normally do is if I change something I just regenerate the metadataclass by adding a new service and deleting the service afterwards and then merge the two keeping my old changes and keeping the newly added entities.

5
4/16/2011 9:35:38 PM

Popular Answer

You cannot unfortunately add any annotations to the properties generated in the POCO.

A possible workaround is to modify the TT template to add the custom annotation that you want for the given property+entity that you want to target only.

I had the same issue in a previous project when I wanted to use the Enterprise Library to implement validation. I ended up creating a partial class and writing methods decorated with annotations instead.

In your case, you can try creating in a partial class a property (with a different name) that returns the EF entity property with an annotation on top.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow