Data Annotations and Entity Framework Code First

I like the code first model of Entity Framework 4 (CTP2 at time of writing). A Domain Entity can be decorated with data annotations which can then be used by the Entity Framework when constructing the database.

I have no concerns adding the System.ComponentModel.DataAnnotations reference to my Domain; I have no intention of changing my DAL and if I change my database it will only be to a different flavour of MS SQL.

There are a number of ‘purposes’ for data annotations but they don’t all sit comfortable within a domain model.

They can represent business rules:

[Key]public string AccountNumber { get; set; }[Required][StringLength(50)]public string Name { get; set; }

The KeyAttribute really could be considered a database hint or a business rule.

They can represent hints to the database:

[StoreGenerated(StoreGeneratedPattern.Identity)]public int AccountNumber { get; set; }

They can also be hints to the UI:

[ScaffoldColumn(false)]public int Id { get; set; }

Whilst I like the idea of keeping all these annotations neatly tucked up inside my model, the purist in me wants to move the UI hints to a view model and the database hints to an entity configuration class in the data layer.

I think I’ll stick with the KISS approach and keep the annotations within my domain model but reserve the right to change my mind. Any comments / views for or against are welcome.

Previous
Previous

Adding Namespaces to MVC3 Views

Next
Next

Entity Framework 4 and SQLCE 4 CTPs Odds and Ends