Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DataAnnotations with Entity Framework

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' */
  }
}
like image 417
dcompiled Avatar asked Jun 08 '10 17:06

dcompiled


People also ask

Does EF core support data annotation attributes?

Configuration enables you to override EF Core's default behaviour. Configuration can be applied in two ways, using the Fluent API, and through DataAnnotation attributes. Attributes are a kind of tag that you can place on a class or property to specify metadata about that class or property.

How do I use system ComponentModel DataAnnotations?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.

How do I create a composite primary key in Entity Framework?

Entity Framework Core supports composite keys - primary key values generated from two or more fields in the database. Composite keys are not covered by conventions or data annotation attributes. The only way to configure composite keys is to use the HasKey method.


1 Answers

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.

like image 140
Michael Finger Avatar answered Oct 13 '22 23:10

Michael Finger