ASP.NET MVC 4, EF5, Unique property in model - best practice?

前端 未结 7 536
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 07:24

ASP.NET MVC 4, EF5, Code First, SQL Server 2012 Express

What is best practice to enforce a unique value in a model? I have a places class that has a

7条回答
  •  借酒劲吻你
    2020-12-13 07:50

    The only way is to update your migration once you generate it, assuming you are using them, so that it enforces a unique constraint on the column.

    public override void Up() {
      // create table
      CreateTable("dbo.MyTable", ...;
      Sql("ALTER TABLE MyTable ADD CONSTRAINT U_MyUniqueColumn UNIQUE(MyUniqueColumn)");
    }
    public override void Down() {
      Sql("ALTER TABLE MyTable DROP CONSTRAINT U_MyUniqueColumn");
    }
    

    The hard bit, though, is enforcing the constraint at the code level before you get to the database. For that you might need a repository that contains the complete list of unique values and makes sure that new entities don't violate that through a factory method.

    // Repository for illustration only
    public class Repo {
      SortedList uniqueKey1 = ...; // assuming a unique string column 
      public Entity1 NewEntity1(string keyValue) {
        if (uniqueKey1.ContainsKey(keyValue) throw new ArgumentException ... ;
        return new Entity1 { MyUniqueKeyValue = keyValue };
      }
    }
    

    References:

    • Repository - Fowler (the original source of Repository)
    • Repostory - MSDN
    • Tutorial: Repository in MVC (www.asp.net)
    • Singleton in C# - SO

    Footnote:

    There are a lot of requests for [Unique] in code first, but it looks like it isn't even making version 6: http://entityframework.codeplex.com/wikipage?title=Roadmap

    You could try voting for it here: http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1050579-unique-constraint-i-e-candidate-key-support

提交回复
热议问题