Entity Framework Core 中的代理项

Proxy Items in Entity Framwork Core

是否可以在 EF Core 中创建为代理元素?

例如,在数据库中有id为1的元素,其名称为Example。 id 为 2 的第二个元素没有名称(为空),但有对元素 1 的引用(“id_replace”)。在这种情况下,我希望第 2 项返回的名称与第 1 项一样是“示例”。还有对第 1 项引用的“包括”引用。

之所以有这么奇怪的想法,是因为我需要把元素链接起来,如果元素1发生变化,元素2也会显示变化。

Example Registers in Database

当然可以。假设您的 class 是:

public class YourClass
{
    public int id { get; set; }
    public string name { get; set; }
    public int? id_replace { get; set; }
}

在您的 class 中,您需要具有一对多引用属性:

    public YourClass parent { get; set; }
    public IList<YourClass> children { get; set; }

然后,在您的 DbContext class 中,在覆盖 OnModelCreating 函数中,您需要在 fluent API 中设置一个关系,表明 id_replace 是一个 self-referencing外键:

modelBuilder.Entity<YourClass>(entity =>
{
     entity.HasOne(x => x.parent)
         .WithMany(x => x.children)
         .HasForeignKey(x => x.id_replace)
         .OnDelete(DeleteBehavior.SetNull);
});

执行此操作(并迁移)后,您将拥有必要的导航属性,可以添加不代表数据库中任何内容的计算属性。所以你的 class 可以有 属性:

    public int alt_name => name??$"\"{parent.name}\"";

所以最终,您的 class 将看起来像这样:

public class YourClass
{
    public int id { get; set; }
    public string name { get; set; }
    public int? id_replace { get; set; }
    public YourClass parent { get; set; }
    public IList<YourClass> children { get; set; }
    public int alt_name => name??$"\"{parent.name}\"";
}

这样,您可以丢弃 name 属性 并只调用 alt_name 属性。您甚至可以将 name 属性 设置为私有或更改名称以避免混淆。