Adding custom property attributes in Entity Framework code

前端 未结 6 1739
迷失自我
迷失自我 2020-12-08 14:43

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

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 15:08

    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.

提交回复
热议问题