Question

I have been looking for a way to make, for example a username unique in the database with Fluent API / Code First. Is this even possible via either of these routes?

Because I can't find any tutorial or example that shows how this is done.

Was it helpful?

Solution

You will have to provide a Context Initializer and override Seed method to initialize your database. There you can add an Unique Index using DbContext.Database.ExecuteSqlCommand. Here is the sample code for the same.

Model

public class Relay  {

    //Scalar Properties
    private int _id;
    [Key]
    public virtual int Id {
        get { return _id; }
        set { SetField(ref _id, value, () => Id); }
    }

    private string _name;
    [MaxLength(100)]
    [Required]
    public virtual string Name {
        get { return _name; }
        set { SetField(ref _name, value, () => Name); }
    }

    //Other properties of Model
}

DBContext

public class RelayContext : DbContext {
     public DbSet<Relay> Relays { get; set; }

    public RelayContext(string connectionString) : 
        base(connectionString) {
        Database.SetInitializer(new RelayContextInitializer());
    }
}

ContextInitializer

public class RelayContextInitializer : CreateDatabaseIfNotExists<RelayContext> {
    protected override void Seed(RelayContext context) {
        context.Database.ExecuteSqlCommand("CREATE UNIQUE INDEX Uix_Relay_Name ON Relays(Name)");
    }
}

That's it. You have now an Unique Index created on Name field of Relays Table.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top