具有 EF 代码优先的唯一密钥
我的项目中有一个以下模型
public class Category
{
public Guid ID { get; set; }
[Required(ErrorMessage = "Title cannot be empty")]
public string Title { get; set; }
}
,我试图将 Title
作为唯一键,我在谷歌上搜索了解决方案,但找不到任何解决方案。 请问有人可以建议我该怎么做吗?
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; }
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不幸的是,您无法首先在代码中将其定义为唯一键,因为 EF 根本不支持唯一键(希望计划在下一个主要版本中使用)。您可以做的是创建自定义数据库初始化程序并通过调用 SQL 命令手动添加唯一索引:
并且您必须在应用程序的引导程序中设置此初始化程序。
编辑
现在(EF 6.1 起)您可以轻松拥有独特的约束,
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:
And you must set this initializer in the bootstrap of your application.
Edit
Now (EF 6.1 onwards )you can easily have unique constrains ,
首先创建自定义属性类:
然后添加到您的类中:
然后在 DbContext 上添加一个初始化程序:
最后在 Global.asax.cs 内的 Application_Start 处添加初始化程序
就是这样。基于 https://stackoverflow.com/a/7426773 的 vb 代码
First create the custom attribute class:
Then add to your classes:
Then add a Initializer on your DbContext:
And for last add the Initializer at Application_Start inside Global.asax.cs
That's it. based on the vb code at https://stackoverflow.com/a/7426773
这是 VB.Net 版本 - 请注意在类级别的泛型实现略有不同。
Here is the VB.Net version - note the implementation of generics that is a little different, at the class level.
我创建了这个类(它是从另一个 Stackoverflow 答案中增强的 -执行一个大型 SQL 脚本(使用 GO 命令)),这允许我将 SQL 脚本放入一个目录中,并在每次需要时执行它们(种子或迁移)。在部署到生产环境后,我不会将其保持打开状态,但在开发过程中,每次重新创建数据库时都可以轻松应用脚本。
}
>
VS 解决方案如下所示:
I create this class (which ws enhanced from another Stackoverflow answer -Execute a large SQL script (with GO commands)), which allows me to drop in the SQL scripts into a directory, and have them all executed each time they are required (Seed, or Migration). I'm not going to leave this open after I deploy to production, but during development it makes it easy to apply scripts each time the DB is recreated.
}
}
Here is what the VS Solution looks like:
我发现这个解决方案虽然没有在 SQL 级别创建唯一键,但它使用 DataAnnotations 验证,请查看:
http://blogs.microsoft.co.il /blogs/shimmy/archive/2012/01/23/validationattribute-that-validates-a-unique-field-against-its-fellow-rows-in-the-database.aspx
I found this solution which although not creating a unique-key in the SQL level, it uses DataAnnotations validation, check it out:
http://blogs.microsoft.co.il/blogs/shimmy/archive/2012/01/23/validationattribute-that-validates-a-unique-field-against-its-fellow-rows-in-the-database.aspx