views:

1048

answers:

3

Is there any way to add custom attributes to properties in EF generated code? The only thing I can see as a plausible solution would be to come up with a custom T4 template. However, because of the nature of the attribute it would be impossible to determine the correct attribute parameter per EF property.

+1  A: 

I don't believe you can. The generator declares all classes as partial allowing you to extend it, but it will not allow you to mark properties with custom attributes as it will simply generate over them. The one thing you can do is write your own entities.

Sergey
This may have been the case, but there are a few options nowadays. See my answer for info.
Drew Noakes
A: 

Daniel Simmons blogs about this here:

http://blogs.msdn.com/dsimmons/archive/2007/09/01/ef-codegen-events-for-fun-and-profit-aka-how-to-add-custom-attributes-to-my-generated-classes.aspx

Darren
This approach is a bit too hardcore given the simple requirement! Thanks for the link though, I hadn't read about this.
Drew Noakes
A: 

You can do this by specifying a metadata type that mirrors the properties and is used simply for attribution.

[MetadataType(typeof(Dinner_Validation))] 
public partial class Dinner 
{} 

public class Dinner_Validation 
{ 
    [Required] 
    public string Title { get; set; } 
}

Steve Smith blogs about it here.

Unfortunately the above approach is brittle to refactoring. Another option is to use the new POCO entities. These avoid compile-time code generation altogether as far as I can tell. I haven't used them yet so can't comment on any pitfalls or tradeoffs.

Drew Noakes