c# - Unique key with EF code first -
i have following model in project
public class category { public guid id { get; set; } [required(errormessage = "title cannot empty")] public string title { get; set; } }
and i'm trying make title
unique key, googled solution, couldn't find any. can suggest me how it, please?
unfortunately can't define unique key in code first because ef doesn't support unique keys @ (it planned next major release). can create custom database intializer , add unique index manually calling sql command:
public class myinitializer : createdatabaseifnotexists<mycontext> { protected override void seed(mycontext context) { context.database.executesqlcommand("create unique index ix_category_title on categories (title)"); } }
and must set initializer in bootstrap of application.
database.setinitializer<mycontext>(new myinitializer());
edit
now (ef 6.1 onwards )you can have unique constrains ,
[index("titleindex", isunique = true)] public string title { get; set; }
Comments
Post a Comment