Sam
Sam

Reputation: 28989

Ensure unique values in Entity Framework 7

I'm using Entity Framework 7 (beta). I want to constraint the values in a field, so no duplicate can be added. With EF6 there was an Index markup which could be used like:

public class MyEntityClass
{ 
    [Index(IsUnique = true)]
    [MaxLength(10)]
    public string MyUniqueProperty{ get; set; } 
}

Sadly this attribute is not present in EF7 - how can I get EF7 to check for uniqueness?

Upvotes: 2

Views: 657

Answers (1)

Thom Kiesewetter
Thom Kiesewetter

Reputation: 7304

Data annotation is not available in beta8 see roadmap

You can set your checks in the onModelCreating If you want to know what is supported add this reference in your project.json

    "EntityFramework.SqlServer.Design": "7.0.0-beta8",

And use scaffold from the command prompt

 dnx ef dbcontext scaffold "connectionstring" EntityFramework.SqlServer

example of generated code

    protected override void OnModelCreating(ModelBuilder builder)
    {
        modelBuilder.Entity<LocalizationsOrg>(entity =>
        {
            entity.Property(e => e.Filename).HasDefaultValue("");

            entity.Property(e => e.LocaleId).HasDefaultValue("");

            entity.Property(e => e.ResourceSet).HasDefaultValue("");

            entity.Property(e => e.Type).HasDefaultValue("");

            entity.Property(e => e.Updated).HasDefaultValueSql("getutcdate()");

            entity.Property(e => e.Value).HasDefaultValue("");

            entity.Property(e => e.ValueType).HasDefaultValue(0);
        });

        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }

Upvotes: 1

Related Questions