What is the best way to add attributes to auto-generated entities (using VS2010 and EF4)

删除回忆录丶 提交于 2019-12-20 01:59:13

问题


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.)


回答1:


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

Adding Attributes to Generated Classes




回答2:


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;
    }



回答3:


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



来源:https://stackoverflow.com/questions/4619609/what-is-the-best-way-to-add-attributes-to-auto-generated-entities-using-vs2010

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!