Does Entity Framework 5 support unique constraints?

后端 未结 5 551
日久生厌
日久生厌 2020-12-10 01:49

Wondering if Entity Framework 5 supports unique constraints on entity properties? If so, how can I specify that a property should be unique?

相关标签:
5条回答
  • 2020-12-10 02:16

    No, it doesn't. There were plans in the past to include a unique constraint feature in EF 5.0:

    http://blogs.msdn.com/b/efdesign/archive/2011/03/09/unique-constraints-in-the-entity-framework.aspx

    But you can see that there is an update on top of the post:

    Update: this feature has been postponed and will not be included in Entity Framework 5.

    You can vote on the feature to raise possibly the priority it gets implemented with...

    http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1050579-unique-constraint-i-e-candidate-key-support

    ...because apparently it isn't even on the roadmap for EF 6.0 at the moment:

    http://entityframework.codeplex.com/wikipage?title=Roadmap

    0 讨论(0)
  • 2020-12-10 02:32

    While unique constraints are still not supported out of the box by EF (version 6.0 as of writing this), there are some workarounds for Code First approach to get the desired behaviour. See an attribute-based solution, as an answer to a similar question. Works with EF 5.0+.

    EDIT:

    Starting with EF 6.1 unique indexes are supported:

    [Index(IsUnique = true)]
    public string EmailAddress { get; set; }
    

    They are the same as the unique constraints for most practical purposes.

    0 讨论(0)
  • 2020-12-10 02:32

    As mentioned above it is not supported but as for now when I create a database programmatically (Code First) I use the following code in the init db section:

    MainDBContext mainDBContext = new MainDBContext();
    
    mainDBContext.Database.ExecuteSqlCommand("ALTER TABLE table_name ADD CONSTRAINT uc_FieldName UNIQUE(FieldName)");
    
    mainDBContext.Dispose();
    
    0 讨论(0)
  • 2020-12-10 02:33

    Well i was looking for solution and finally i found it. when you generate migration in code you can create unique key

     CreateTable(
                    "dbo.TaBLE",
                    c => new
                        {
                            Id = c.Int(nullable: false, identity: true),
                            Date = c.DateTime(nullable: false),
                            Meter_Id = c.Int(),
                        })
                    .PrimaryKey(t => t.Id)
    
                    .Index(t => new {t.Meter_Id, t.Date}, true);
    

    Validation before insert you can do on BLL level, so i think it can solve your problem.

    0 讨论(0)
  • 2020-12-10 02:34

    I found a work-around in order to achieve unique constraints on entity properties. It's really and intuitive. Please refer to my other post:

    https://stackoverflow.com/a/16496291/1873113

    0 讨论(0)
提交回复
热议问题