Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I have used a data validation in the code behind of edmx file of entity framework as:
[Range(1, 5, ErrorMessage = "Enter a value between 1 and 5")]
C#
public global::System.Decimal UnitPrice
        {
            get
            {
                return _UnitPrice;
            }
            set
            {
                OnUnitPriceChanging(value);
                ReportPropertyChanging("UnitPrice");
                _UnitPrice = StructuralObject.SetValidValue(value);
                ReportPropertyChanged("UnitPrice");
                OnUnitPriceChanged();
            }
        }


When I use this entity on consuming application then it does not check the range validation.
Posted

1 solution

To achieve this you have to create a 2nd partial class for each entity class in EF and link it to a auxiliary class with substitute properties.

for example you have a generated
C#
class Product { public int UnitPrice{ get; set; } }

The generated class will always be marked as partial.

and now you have to create 2nd partial class file and add

C#
[MetadataType(typeof(ProductMetadata))]
public partial class Product 
{
    // it's possible to add logic and non-mapped properties here
}


public class ProductMetadata
{
   [Range(1, 5, ErrorMessage = "Enter a value between 1 and 5")]
    public int UnitPrice { get; set; }   // note the 'object' type
}


It will work.
Rate it if you find it as useful.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900