views:

106

answers:

1

We're using sqlmetal to generate our DBML, run it through a transformation, then use sql metal to generate the DataContext classes -- additionally, I want to automatically generate some validation for the entities based on some metadata that we store in the database about each entity and it's attributes. For example, if an entity has what I know to be an "EmailAddress" field of meta type "Email", I'd like to create the OnValidate method for the Email entity to check that it adheres to my regular expression. That's all fine and dandy, and I can do it like this in another file:

public partial class MYENTITY
{
    partial void OnValidate(System.Data.Linq.ChangeAction action)
    {
        if(action != System.Data.Linq.ChangeAction.Delete)
        {
            //check the validity of my email field or anything else
        }
    }
}

How can I do this while still allowing the developers who want to use this DataContext the ability to hook their own logic into the OnValidate method for this entity? In our situation, this would be business logic specific to the application being developed. The additions I describe above are just safeguards to ensure that data that is getting to the database is as I expect it to be.

Thanks for any help. New here, so apologies if I did something wrong.

A: 

If I understand you correctly, you want to be able to dynamically generate the OnValidate method in a particular file using your metada, but still allow for your developers to add customizations to the OnValidate method? One way, would be to generate the code using this template:

public partial class MYENTITY
{
    partial void OnValidateCustomization();

    public void OnValidate(System.Data.Linq.ChangeAction action)    
    {        
        if(action != System.Data.Linq.ChangeAction.Delete)        
        {            
            //hook for code generator
        }   
        OnValidateCustomization();
    }
}

And have your developers, in another file or in the same file depending on how you handle existing files when running your dynamic code file generation, implement the OnValdateCustomization() method:

public partial class MYENTITY
{
    partial void OnValidateCustomization()
    {
         Console.WriteLine("I Worked.");
    }
}

However, I am making assumptions about how you are dynamically generating code. Could you not also put tokens in the files generated and allow for modification of the files instead of just copying over them when you again run the dynamic code generator? So you just inject at those tokens instead of replacing the whole file? Argh, it's the missing details...

Merritt