Continuing with previous post, I wanted to go over data annotations, some old and some new in CTP 5. Of course, everything you can do with data annotations, you can do with fluent API. Once important this to remember about data annotations is that they are used for validation as well as defining columns in database. All data annotations are implemented as attributes. Here are some of the attributes to remember. Each class defines a table in the database of course. Attributes can be used to decorate a class, by primary are used to decorate class property that become columns in a database.
- [Key] – specified which column or columns comprise a primary key for a table.
- [StringLength] – specifies maximum length, and optionally minimum length. Minimum length is only used for validation, not database constraints.
- [MaxLength] – can be used instead of StringLenth to specify maximum length for a column
- [ConcurrencyCheck] – flags columns that participate in optimistic concurrency checks.
- [Required] – specifies that a value is required for a property. Column is flagged as not nullable.
- [Timestamp] – flags time stamp columns that are typically used for concurrency checks
- [Column] – can be used to specify a column name. If omitted, property name becomes column name. You can also use this attribute to control ordinal position of a column.
- [Table] – can be used to specify a table name. If omitted, class name becomes table name.
- [DatabaseGenerated] can be used to signal that a data is populated via a database. Possible values are Computed, Identity or None. None is the default.
- [NotMapped] added in this release. Allows you to have a property in a class without generating a column in a database.
- [ForeignKey] and [InverseProperty] are used for foreign key columns
This release also included pluggable conventions preview. Conventions control various aspects of behavior of code first entity framework release. For example, pluralization of table names. You can also write your own conventions and attributes to control behavior of the entity framework. This is extremely powerful feature that pretty much allows you to customize database generation to unlimited extent.