简体   繁体   English

Entity Framework 6 中的单行表

[英]Single Row Table in Entity Framework 6

I couldn't find a solution for this problem but the title makes clear what I want.我找不到解决此问题的方法,但标题清楚地说明了我想要什么。

Is it possible to create a single row table (I only need to store a boolean value in a table)?是否可以创建单行表(我只需要在表中存储一个 boolean 值)? And how can I configure this constraint with Fluent API?以及如何使用 Fluent API 配置此约束?

you could make one of the columns as primary and also allow only one value. 您可以将其中一列作为主列,也只允许一个值。 unfortunately fluent api currently doenst support default value 不幸的是,流畅的api目前最不支持默认值

public class StatusIdentifer
{
  [DefaultValue("1")]
  [Key]
  public int id {get; set}; //set can be removed here?
  public bool status {get:set;} //your boolean value
}

the trick is not to expose any set methods for id. 诀窍是不要暴露任何set方法。

at database level you can still break the paradigm. 在数据库级别,你仍然可以打破范式。 The answer here tells how to create a check constraint 这里的答案说明了如何创建检查约束

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...");
            }
        }

With a bit of research I came up with this solution. 通过一些研究,我想出了这个解决方案。 I created an Initializer for the database (because ExecuteSqlCommand cannot be invoked in the OnModelCreating method). 我为数据库创建了一个初始化程序(因为无法在OnModelCreating方法中调用ExecuteSqlCommand)。

class UserDbInitializer : CreateDatabaseIfNotExists<UserDbContext>
{
    protected override void Seed(UserDbContext context)
    {
        context.Database.ExecuteSqlCommand(
            "CREATE TABLE __Lock(" +
            "Id char(1) NOT NULL DEFAULT 'X'," +
            "Lock bit NOT NULL," +
            "CONSTRAINT PK_LOCK PRIMARY KEY (Id)," +
            "CONSTRAINT CK_LOCK_Locked CHECK (Id='X'))"
        );

        context.Database.ExecuteSqlCommand(
            "INSERT INTO __Lock VALUES('X', 0)"
        );

        base.Seed(context);
    }
}

And in the UserDbContext is following property: 在UserDbContext中有以下属性:

public bool Locked
{
    get
    {
        return Database.SqlQuery<bool>("SELECT Lock FROM __Lock").SingleAsync().Result;
    }
    set
    {
        if (value)
            Database.ExecuteSqlCommand("UPDATE __Lock SET Lock = 1");
        else
            Database.ExecuteSqlCommand("UPDATE __Lock SET Lock = 0");
    }
}

Hope this helps for others :) 希望这对其他人有帮助:)

In EF Core you can set the check constraint for the primary key.在 EF Core 中,您可以为主键设置检查约束。 It enforces that column Id must have value that is equal to 1.它强制列Id的值必须等于 1。

modelBuilder.Entity<YourTable>(e =>
{
   e.HasCheckConstraint("CK_Table_Column", "[Id] = 1");

   e.HasData(...) //optionally add some initial date for Id = 1
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM