I can't find way to add a unique constraint to my field with using attribute:
public class User
{
[Required]
public int Id { get; set; }
[Required]
// [Index("IX_FirstAndSecond", 2, IsUnique = true)] not supported by core
public string Email { get; set; }
[Required]
public string Password { get; set; }
}
I'm using these packages:
"Microsoft.EntityFrameworkCore": "1.0.1",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
Entity Framework (EF) Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework data access technology. EF Core can serve as an object-relational mapper (O/RM), which: Enables . NET developers to work with a database using . NET objects.
You can also configure multiple properties to be the key of an entity - this is known as a composite key. Composite keys can only be configured using the Fluent API; conventions will never set up a composite key, and you can not use Data Annotations to configure one.
EF Core only supports one index per distinct set of properties.
On EF core you cannot create Indexes using data annotations.But you can do it using the Fluent API.
Like this inside your {Db}Context.cs
:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique();
}
...or if you're using the overload with the buildAction:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<User>(entity => {
entity.HasIndex(e => e.Email).IsUnique();
});
}
You can read more about it here : Indexes
Also if you want to create Unique constrains on multiple columns you can simply do this (following @Sampath's link)
class MyContext : DbContext
{
public DbSet<Person> People { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasIndex(p => new { p.FirstName, p.LastName })
.IsUnique(true);
}
}
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With