entity framework 5 - Unique fields in table Fluent Api / Code First -


i have been looking way make, example username unique in database fluent api / code first. possible via either of these routes?

because can't find tutorial or example shows how done.

you have provide context initializer , override seed method initialize database. there can add unique index using dbcontext.database.executesqlcommand. here sample code same.

model

public class relay  {      //scalar properties     private int _id;     [key]     public virtual int id {         { return _id; }         set { setfield(ref _id, value, () => id); }     }      private string _name;     [maxlength(100)]     [required]     public virtual string name {         { 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. have unique index created on name field of relays table.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -