问题
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:
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.
回答2:
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.
回答3:
I believe you have to mark your property as partial as well.
Actually I think you also will want to remove the override (because you aren't overriding a parent property.)
来源:https://stackoverflow.com/questions/5689696/override-entity-framework-entity-property