繁体   English   中英

实体框架核心中的代理项

[英]Proxy Items in Entity Framwork Core

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

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

我之所以有这样一个奇怪的想法,是因为我需要链接元素,如果元素 1 发生变化,所做的变化也会显示在元素 2 上。

数据库中的示例寄存器

你当然可以。 假设你的 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 function 中,您需要在流利的 API 中设置一个关系,指示 id_replace 是一个自引用外键:

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属性设置为私有或更改名称以避免混淆。

暂无
暂无

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

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