Using DataAnnotations with Entity Framework

前端 未结 2 1509
余生分开走
余生分开走 2020-11-27 07:31

I have used the Entity Framework with VS2010 to create a simple person class with properties, firstName, lastName, and email. If I want to attach DataAnnotations like as is

相关标签:
2条回答
  • 2020-11-27 07:53

    You need to either use a metadata "buddy" class or (my preference) project onto a presentation model instead of binding views directly to entities.

    0 讨论(0)
  • 2020-11-27 07:55

    A buddy class is more or less the direction your code snippet is journeying, except your manually coded partial Person class would have an inner class, like:

    [MetadataType(typeof(Person.Metadata))]
    public partial class Person {
        private sealed class MetaData {
            [RegularExpression(...)]
            public string Email { get; set; }
        }
    }
    

    Or you could have your manually partial Person class and a separate Meta class like:

    [MetadataType(typeof(PersonMetaData))]
    public partial class Person { }
    
    public class PersonMetaData {
    [RegularExpression(...)]
    public string Email;
    }
    

    These are workarounds and having a mapped Presentation class may be more suitable.

    0 讨论(0)
提交回复
热议问题