Question

ASP.NET MVC2 has strong support for using attributes on entities (validation, and extending Html helper class and more).

If I generated my Model from the Database using VS2010 EF4 Entity Data Model (edmx and it's cs class), And I want to add attributes on some of the entities. what would be the best practice ? how should I cope with updating the model (adding more fields / tables to the database and merging them into the edmx) - will it keep my attributes or generate a new cs file erasing everything ?

(Manual changes to this file may cause unexpected behavior in your application.)

(Manual changes to this file will be overwritten if the code is regenerated.)

Was it helpful?

Solution

Generally you'd create what is called partial classes to extend your auto-generated objects.

Adding Attributes to Generated Classes

OTHER TIPS

With the "buddy class" concept, linked above, and data annotations I use this extention method. I forget where I got it, so kudos to the original author.

We use it like

 List<ValidationResult> errorList = new List<ValidationResult>();
        bool bValid = client.IsValid<Client, ClientMetadata>(ref errorList, false);


    public static bool IsValid<T, U>(this T obj, ref List<ValidationResult> errors, bool validateAllProperties = true) where T : IValidatableObject
    {
        //If metadata class type has been passed in that's different from the class to be validated, register the association
        if (typeof(T) != typeof(U))
        {
            TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(T), typeof(U)), typeof(T));
        }

        var validationContext = new ValidationContext(obj, null, null);
        var validationResults = new List<ValidationResult>();
        Validator.TryValidateObject(obj, validationContext, validationResults, validateAllProperties);

        errors = validationResults;

        if (validationResults.Count > 0)
            return false;
        else
            return true;
    }

We use partial classes, but if you need them persisted and handled by EF, the "Update Model from Database" option is your best friend.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top