EF5 Code First:检测它是否创建了数据库,以便我可以运行ALTER语句

时间:2013-04-18 12:36:40

标签: c# .net sql entity-framework

我是Entity Framework 5的新手。我们的团队正在使用Code First工作流程。

在我开始讨论我的主要问题之前,让我首先向您展示我尝试过的内容 有史以来的最终评论:D

public class MyDBContext : CDBContext
{
    public MyDBContext() : base(connString) { }

    public MyDBContext(string connStr) : base(connStr) { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // removes some conventions
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
        // ........

        // model configurations which contains mappings
        modelBuilder.Configurations.Add(new AccountConfiguration());
        // ........

        // calls base OnModelCreating
        base.OnModelCreating(modelBuilder);
    }

    // list of all Entity
    public DbSet<Account> Account { get; set; }
}

MyDBContext是我创建的类,它继承自CBDContext,包含覆盖方法,并且也继承自DBContext。我遇到的一个问题是实体框架不处理字段唯一性。我已经在他们的网站上阅读了Configuring/Mapping Properties and Types with the Fluent API上的文章,我找不到任何配置来将属性设置为唯一。

所以我为了设置字段唯一而做的是在创建过程中手动运行几个ALTER sql语句,

using (MyDBContext _context = new MyDBContext(connString))
{
    if (_context.Database.CreateIfNotExists()) 
    {
        _context.Database.ExecuteSqlCommand("ALTER TABLE Account ADD CONSTRAINT UQ_Account_AccountNumber UNIQUE(AccountNumber)");
        _context.Database.ExecuteSqlCommand("ALTER TABLE Account ADD CONSTRAINT UQ_Account_GUID UNIQUE(GUID)");
        // .... more on this in the following lines ...
    }
}

我的问题:

  1. 我是否正确实体框架没有任何配置或数据注释 设置字段唯一
  2. 有没有办法在运行时检测或知道EF是否创建了数据库,所以我可以将此语句if (_context.Database.CreateIfNotExists())移动或隐藏到某个可以覆盖的可用方法?
  3. 我真正想要的是从使用状态中移除if (_context.Database.CreateIfNotExists())并将其放在其他地方或MyDBContext内,以便我的代码看起来像这样,

    using (MyDBContext _context = new MyDBContext(connString))
    {
        Account _acc = new Account()
        // ...Account properties ...
    
        _context.Account.Add(_acc);
        _context.SaveChanges();
    }
    

    感谢。

2 个答案:

答案 0 :(得分:4)

您应该查看Code First Migrations,更具体地在 Data Motion / Custom SQL 及其后续部分 - 这可能是实现所需结果的方法。您的迁移类可能如下所示:

public partial class AddUniqueConstrains : DbMigration
{
    public override void Up()
    {
        Sql("ALTER TABLE Account ADD CONSTRAINT UQ_Account_AccountNumber UNIQUE(AccountNumber)");
        Sql("ALTER TABLE Account ADD CONSTRAINT UQ_Account_GUID UNIQUE(GUID)");
    }

    public override void Down()
    {
        Sql("ALTER TABLE Account DROP CONSTRAINT UQ_Account_AccountNumber UNIQUE");
        Sql("ALTER TABLE Account DROP CONSTRAINT UQ_Account_GUID");
    }
}

您还可以探索此问题的答案中描述的其他选项:Unique Constraint in Entity Framework Code First

答案 1 :(得分:1)

如果您不使用(或不能使用)EF迁移,您可以使用this answer中提到的自定义初始化程序。创建数据库后,自定义初始值设定项将执行Seed方法=仅在数据库不存在时执行一次。如果您需要逐步开发数据库初始化程序本身不会帮助您(这是迁移的目的)。