与EF code唯一键第一 [英] Unique key with EF code first

查看:512
本文介绍了与EF code唯一键第一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的模型在我的项目

I have a following model in my project

public class Category
{   
    public Guid ID { get; set; }
    [Required(ErrorMessage = "Title cannot be empty")]
    public string Title { get; set; }
}

和我试图让标题作为唯一的键,我用Google搜索解决方案,但找不到任何。
可以在任何建议我该怎么做,好吗?

and I'm trying to make Title as unique key, I googled for the solution, but couldn't find any. Can any suggest me how to do it, please?

推荐答案

可惜你不能定义code首先它作为唯一的关​​键,因为EF根本不支持唯一的密钥(这是希望计划于明年主要版本)。你可以做的就是创建自定义数据库初始化器和手动调用SQL命令添加唯一索引:

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());

修改

现在(EF 6.1起),你就可以轻松拥有独特的约束,

Now (EF 6.1 onwards )you can easily have unique constrains ,

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

这篇关于与EF code唯一键第一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆