码迷,mamicode.com
首页 > 其他好文 > 详细

EntityFramework Code First 添加唯一键

时间:2016-02-25 13:32:40      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

在EntityFramework 6.1后可以直接使用

[Index("TitleIndex", IsUnique = true)]
 public string Title { get; set; }

在旧版本中,

Unfortunately you can‘t define it as unique key in code first because EF doesn‘t support unique keys at all (it is hopefully planned for next major release). What you can do is to create custom database intializer and add unique index manually by calling SQL command:

public class MyInitializer : CreateDatabaseIfNotExists<MyContext>
{
  protected override void Seed(MyContext context)
  {
    context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX IX_Category_Title ON Categories (Title)");
  }
}

And you must set this initializer in the bootstrap of your application.

Database.SetInitializer<MyContext>(new MyInitializer());

http://stackoverflow.com/questions/5701608/unique-key-with-ef-code-first

 

EntityFramework Code First 添加唯一键

标签:

原文地址:http://www.cnblogs.com/dupeng0811/p/unique-key-with-ef-code-first.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!