Add Data Annotation to Entity Framework (or Linq to SQL) Class Generated

Can I add another Data Anootation element, such as Range , Required , ... in the Entity Framework or Linq to SQL automatically generated classes?

I want to use data annotation check for my classes

thanks

Important: regarding this topic: using metadata with the Entity Framework to verify the use of data annotation

EDIT 1)

I create an entity framework model for the Northwind database and add a Product class. And the code part looks like this:

 [EdmEntityTypeAttribute(NamespaceName="NorthwindModel", Name="Product")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Product : EntityObject { #region Factory Method /// <summary> /// Create a new Product object. /// </summary> /// <param name="productID">Initial value of the ProductID property.</param> /// <param name="productName">Initial value of the ProductName property.</param> /// <param name="discontinued">Initial value of the Discontinued property.</param> public static Product CreateProduct(global::System.Int32 productID, global::System.String productName, global::System.Boolean discontinued) { Product product = new Product(); product.ProductID = productID; product.ProductName = productName; product.Discontinued = discontinued; return product; } #endregion #region Primitive Properties /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 ProductID { get { return _ProductID; } set { if (_ProductID != value) { OnProductIDChanging(value); ReportPropertyChanging("ProductID"); _ProductID = StructuralObject.SetValidValue(value); ReportPropertyChanged("ProductID"); OnProductIDChanged(); } } } private global::System.Int32 _ProductID; partial void OnProductIDChanging(global::System.Int32 value); partial void OnProductIDChanged(); 

I want ProductID to be required, but I cannot write code this way:

 public partial class Product { [Required(ErrorMessage="nima")] public global::System.Int32 ProductID; } 
+7
source share
1 answer

Yes. You need to create a second partial class for each object and associate it with a helper class with replacement properties.

Suppose you have a generated partial class Customer { public string Name { get; set; } } partial class Customer { public string Name { get; set; } }
The generated class will always be marked as partial.

Then you need to add the file with:

 [MetadataType(typeof(CustomerMetadata))] public partial class Customer { // it possible to add logic and non-mapped properties here } public class CustomerMetadata { [Required(ErrorMessage="Name is required")] public object Name { get; set; } // note the 'object' type, can be anything } 

Personally, I do not think this is a very elegant solution, but it works.

+8
source

All Articles