实体框架代码中的唯一约束首先

实体框架代码中的唯一约束首先

本文介绍了实体框架代码中的唯一约束首先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

可以使用流畅的语法或属性来定义属性的唯一约束吗?如果没有,什么是解决方法?

Is it possible to define a unique constraint on a property using either the fluent syntax or an attribute? If not, what are the workarounds?

我有一个主键的用户类,但我想确保电子邮件地址也是唯一的。是否可以直接编辑数据库?

I have a user class with a primary key, but I would like to make sure the email address is also unique. Is this possible without editing the database directly?

解决方案(基于Matt的答案)

public class MyContext : DbContext {
    public DbSet<User> Users { get; set; }

    public override int SaveChanges() {
        foreach (var item in ChangeTracker.Entries<IModel>())
            item.Entity.Modified = DateTime.Now;

        return base.SaveChanges();
    }

    public class Initializer : IDatabaseInitializer<MyContext> {
        public void InitializeDatabase(MyContext context) {
            if (context.Database.Exists() && !context.Database.CompatibleWithModel(false))
                context.Database.Delete();

            if (!context.Database.Exists()) {
                context.Database.Create();
                context.Database.ExecuteSqlCommand("alter table Users add constraint UniqueUserEmail unique (Email)");
            }
        }
    }
}


推荐答案

据我所知,目前实体框架无法做到这一点。但是,这不仅仅是唯一约束的问题...您可能希望创建索引,检查约束以及可能的触发器和其他构造。 这是一个简单的模式,您可以使用你的代码首先设置,但不可否认,它不是数据库不可知的:

As far as I can tell, there's no way to do this with Entity Framework at the moment. However, this isn't just a problem with unique constraints... you may want to create indexes, check constraints, and possibly triggers and other constructs too. Here's a simple pattern you can use with your code-first setup, though admittedly it's not database agnostic:

public class MyRepository : DbContext {
    public DbSet<Whatever> Whatevers { get; set; }

    public class Initializer : IDatabaseInitializer<MyRepository> {
        public void InitializeDatabase(MyRepository context) {
            if (!context.Database.Exists() || !context.Database.ModelMatchesDatabase()) {
                context.Database.DeleteIfExists();
                context.Database.Create();

                context.ObjectContext.ExecuteStoreCommand("CREATE UNIQUE CONSTRAINT...");
                context.ObjectContext.ExecuteStoreCommand("CREATE INDEX...");
                context.ObjectContext.ExecuteStoreCommand("ETC...");
            }
        }
    }
}

另一个选项是如果您的域模型是在数据库中插入/更新数据的唯一方法,则可以自己实现唯一性要求,并将数据库从其中删除。这是一个更便携的解决方案,并强制您清楚您的代码中的业务规则,但让您的数据库可以打开无效的数据回退。

Another option is if your domain model is the only method of inserting/updating data in your database, you could implement the uniqueness requirement yourself and leave the database out of it. This is a more portable solution and forces you to be clear about your business rules in your code, but leaves your database open to invalid data getting back-doored.

这篇关于实体框架代码中的唯一约束首先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 00:22