Richard
Richard

Reputation: 1106

Do you need Data Annotations for Entity Framework Database First? ie Key, Required

I do Entity Framework Database First.

There is a lot of inconsistency with our C# Entity Classes where some have Data Annotations and some do not. (Many different developers over the years and a lot of cutting and pasting)

For example in the code below the table CoverageFactor already exists in the database.

Is there any benefits to specifying the columns that are Key and Required? Since the primary key and if nulls are allowed has already been defined for the column, I would think not.

If the database column names and property names are the same, is there any benefit to having the Column and Order Data Annotation.

Finally what about the Table Data Annotation? Again the values of the table and the class names are the same.

I am just trying to declutter our code and be consistent.

Any advice would be appreciated.

[Table("CoverageFactor")]
public class CoverageFactor 
{

    [Key]
    [Required]
    [Column("Term", Order = 1)]
    public int Term { get; set; }

    [Required]
    [Column("Factor")]
    public decimal Factor { get; set; }

    [Key]
    [Required]
    [Column("EffectiveDate", Order = 2)]
    public DateTime EffectiveDate { get; set; }

    [Column("EndDate")]
    public DateTime? EndDate { get; set; }

Upvotes: 0

Views: 649

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 88852

EF requires each Entity to have a Key.

RequiredAttribute can be used in client-side Validation

Column and Table mappings can be safely removed if the names are the same, but provide documentation and enable developers to change the class and property names without breaking the application.

All of this mapping can alternatively be moved to OnModelCreating.

Upvotes: 2

Related Questions