EntityFramework Code First 添加唯一键
生活随笔
收集整理的這篇文章主要介紹了
EntityFramework Code First 添加唯一键
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在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
?
總結(jié)
以上是生活随笔為你收集整理的EntityFramework Code First 添加唯一键的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS SDK具体解释之UIDevice
- 下一篇: HDFS Client 设计实现解析