如何让实体框架在防止重复的同时创建和管理数据库表关系

本文关键字:创建 管理 关系 数据库 实体 框架 | 更新日期: 2023-09-27 18:33:04

我正在尝试创建一个UserPreferences表,该表将包含5个布尔值的每个组合,并将让实体框架自动管理保存和检索组合,以便; 如果 UserPreferences 表中不存在布尔值的传入组合,则将创建该组合,如果传入组合已存在,则将使用现有值,而不是创建具有相同组合的重复条目。

我知道还有其他方法可以在不依赖 EF 的情况下执行此操作,但我的问题是:有没有办法通过让实体框架创建和管理关系来实现这一点?

下面是 Customer 类和 UserPreferences 类之间的关系:

public class Customer
{
    public string MyId { get; set; }
    public UserPreferences Preferences { get; set; }
}
public class UserPreferences
{
    public bool Bool1 { get; set; }
    public bool Bool2 { get; set; }
    public bool Bool3 { get; set; }
    public bool Bool4 { get; set; }
    public bool Bool5 { get; set; }
}

注意:我使用的是 .Net 框架 4.5 和 EF 6。

我试图通过在 DbContext 中配置复合主键来解决此问题,但这不起作用,我还尝试从 5 个布尔值创建一个复合主键,但这会导致我的 Customer 表上有额外的行:

public override void Up()
{
    CreateTable(
        "dbo.UserPreferences",
        c => new
            {
                Bool1 = c.Boolean(nullable: false),
                Bool2 = c.Boolean(nullable: false),
                Bool3 = c.Boolean(nullable: false),
                Bool4 = c.Boolean(nullable: false),
                Bool5 = c.Boolean(nullable: false),
            })
        .PrimaryKey(t => new { t.Bool1, t.Bool2, t.Bool3, t.Bool4, t.Bool5 });
    AddColumn("dbo.Customer", "UserPreferences_Bool1", c => c.Boolean());
    AddColumn("dbo.Customer", "UserPreferences_Bool2", c => c.Boolean());
    AddColumn("dbo.Customer", "UserPreferences_Bool3", c => c.Boolean());
    AddColumn("dbo.Customer", "UserPreferences_Bool4", c => c.Boolean());
    AddColumn("dbo.Customer", "UserPreferences_Bool5", c => c.Boolean());
    CreateIndex("dbo.Customer", new[] { "UserPreferences_Bool1", "UserPreferences_Bool2", "UserPreferences_Bool3", "UserPreferences_Bool4", "UserPreferences_Bool5" });
    AddForeignKey("dbo.Customer", new[] { "UserPreferences_Bool1", "UserPreferences_Bool2", "UserPreferences_Bool3", "UserPreferences_Bool4", "UserPreferences_Bool5" }, "dbo.UserPreferences", new[] { "Bool1", "Bool2", "Bool3", "Bool4", "Bool5" });
    DropColumn("dbo.Customer", "UserPreferences");
}

我不确定如何让实体框架来创建和管理关系,也许有一种更简单的方法可以做到这一点,但我忽略了?任何帮助将不胜感激。

如何让实体框架在防止重复的同时创建和管理数据库表关系

你想要创建一个外键。

若要在实体框架中执行此操作,请将类更改为如下所示。UserPreferencesID告诉我们 EF,客户与单个用户首选项密切相关。将virtual应用于 Preferences 属性将允许 EF 根据属性的 ID 自动填充表中属性的值。

public class Customer
{
    public string MyId { get; set; }
    public int UserPreferencesID { get; set; }
    public virtual UserPreferences Preferences { get; set; }
}
public class UserPreferences
{
    public int ID { get; set; }
    public bool Bool1 { get; set; }
    public bool Bool2 { get; set; }
    public bool Bool3 { get; set; }
    public bool Bool4 { get; set; }
    public bool Bool5 { get; set; }
}

FWIW,我不会这样做。这听起来像是吹毛求疵,但这不是一个规范化的设计。谁将保证用户设置中始终涉及 5 个布尔值?我建议的是——

  • 将设置表创建为名称-值对,其中每个用户当前可以有 5 条记录。也许将来会更少或更多。
  • 允许每个用户拥有自己的一组设置。它几乎不需要任何存储空间,并且可以防止对现有设置组合进行不必要的搜索。如果多个用户具有相同的设置,谁在乎?
  • 如果您坚持按照自己的方式进行操作(也许出于我不知道的原因(,我会预先插入 32 种组合,因此您始终只能进行查找。无论如何,所有组合迟早都会在那里。