EntityFramework Code First 添加唯一键
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EntityFramework Code First 添加唯一键相关的知识,希望对你有一定的参考价值。
在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 添加唯一键的主要内容,如果未能解决你的问题,请参考以下文章
EntityFramework Code-First 简易教程-------领域类的配置
EntityFramework Code-First 简易教程-------领域类配置之DataAnnotations
EntityFramework Code-First 简易教程-------领域类配置之Fluent API
C#+EntityFramework编程方式详细之Code First 数据迁移