实体框架 - 具有唯一值的列 [英] Entity Framework - columns with unique values
本文介绍了实体框架 - 具有唯一值的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的实体:
public class User
{
public string Name { get; set; }
public string LastName { get; set; }
public string Username { get; set; } // this is an EmailAddress
[Key]
public Guid Id { get; set; }
}
我如何定义的的用户名是唯一的吗?
How can I define the Username
to be unique too?
我不能将它作为第二个关键...
I cannot set it as a second Key...
使用实体框架6.1.3
Using Entity Framework 6.1.3
推荐答案
如果您使用的是最新的EF(6.1以上),那么你可以使用这个code:
If you’re using the newest EF (6.1+) then you can use this code:
[Index("UserNameIndex", IsUnique = true)]
[MaxLength(100)]
public string UserName { get; set; }
与早期版本的EF还有更复杂的方法,你可以点击这里:的与EF code首先唯一键
这篇关于实体框架 - 具有唯一值的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文