2014-02-12 22:25:00
A collation of useful annotations.
Table
[Table("tblBlog", Schema="journal")] public class Blog { ... }
This example has a different table name from the class name and is in a schema other than dbo. This is useful when connecting to existing databases and it is not appropriate to carry forwards the name into the application.
Primary Key Field
[Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int BlogId { get; set; }
DatabaseGeneratedOption
can have three options None
, Identity
and Computed
.
Composite Keys
public class UserRole {[Key] [Column(Order = 1)] public int UserId { get; set; }[Key] [Column(Order = 2)] public int RoleId { get; set; } }
Null Fields
A column is nullable if a property is nullable.
[Required] public string Name { get; set; }[Required] public Author Author { get; set; }
Field
[Column("BlogName", TypeName="VARCHAR")] [MaxLength(450)] [Required] public string Name { get; set; }
Note that the field name is different from the property name.
Field Index
[Index] public int Rating { get; set; }[Index("PostRatingIndex")] public int Rating { get; set; }
An index in multiple columns
[Index("IX_AuthorStudentCount", 1)] public int AuthorId{ get; set; }[Index("IX_AuthorStudentCount", 2)] public int StudentCount{ get; set; }
Unique Index
[Index(IsUnique = true)] public string Name { get; set; }
Field Database Generated
[DatabaseGenerated(DatabaseGeneratedOption.Computed)] public DateTime DateCreated { get; set; }
Foreign Keys
Method 1
Explicity link the foreign key id with the parent entity, with an annotation.
public class Course {[ForeignKey("Author")] public string AuthorId { get; set; } public Author Author { get; set; } }
Method 2
Explicity link the parent entity with the foreign key id, with an annotation.
public class Course { public string AuthorId { get; set; }[ForeignKey("AuthorId")] public Author Author { get; set; } }