Using DataAnnotations with Entity Framework

让人想犯罪 __ 提交于 2019-11-26 06:46:17

问题


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 done in this blog post I have a small problem because my person class is dynamically generated. I could edit the dynamically generated code directly but any time I have to update my model all my validation code would get wiped out.

First instinct was to create a partial class and try to attach annotations but it complains that I\'m trying to redefine the property. I\'m not sure if you can make property declarations in C# like function declarations in C++. If you could that might be the answer. Here\'s a snippet of what I tried:

namespace PersonWeb.Models
{
  public partial class Person
  {
    [RegularExpression(@\"(\\w|\\.)+@(\\w|\\.)+\", ErrorMessage = \"Email is invalid\")]
    public string Email { get; set; } 
    /* ERROR: The type \'Person\' already contains a definition for \'Email\' */
  }
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/2999936/using-dataannotations-with-entity-framework

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