I am using Entity Framework 4.3 and using Code Fist.
I have a class
public class User
{
public int UserId{get;set;}
public string UserName{get;set;}
}
How do I tell Entity Framework that UserName has to be unique when creating database table?
I would prefer to use data anotations instead of configuration file if possible.
Best Answer
In Entity Framework 6.1+ you can use this attribute on your model:
You can find it in this namespace:
If your model field is a string, make sure it is not set to nvarchar(MAX) in SQL Server or you will see this error with Entity Framework Code First:
The reason is because of this:
(from: http://msdn.microsoft.com/en-us/library/ms191241.aspx )
You can solve this by setting a maximum string length on your model:
Your model will look like this now in EF CF 6.1+:
Update:
if you use Fluent:
and use in your modelBuilder:
Update 2
for EntityFrameworkCore see also this topic: https://github.com/aspnet/EntityFrameworkCore/issues/1698
Update 3
for EF6.2 see: https://github.com/aspnet/EntityFramework6/issues/274
Update 4
ASP.NET Core Mvc 2.2 with EF Core: