Code First方式建立主鍵可以不需要注釋,遵循約定即可,即屬性命名為 Id、ID 、類名加Id都可以,也可加上注釋[key],如果是int類型自動定為自增鍵,這個很友善。其他的屬性建立索引,原來的方式為屬性上添加注釋:
[Index(IsUnique = true)]//這種方式已不适用。
[StringLength(200)]
public string Username { get; set; }
而現在方式上有了重大改變,是在Model類上添加注釋:
[Index("Username",IsUnique = true)]
public class User
{
public int UserId { get; set; }
[StringLength(200)]
public string Username { get; set; }
public string DisplayName { get; set; }
}
同時建立聯合索引(Multiple-Column 索引)也是以有了改變,看起來更加友善:
[Index("BlogId","Rating",IsUnique = true)]
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
// [Index("IX_BlogIdAndRating", 2)]
public int Rating { get; set; }
//[Index("IX_BlogIdAndRating", 1)]
public int BlogId { get; set; }
}