[英]Proxy Items in Entity Framwork Core
Is it possible to create as a proxy element in EF Core?是否可以在 EF Core 中创建为代理元素?
For example, in the database there is the element with the id 1, which has the name Example
.例如,在数据库中有 id 为 1 的元素,其名称为
Example
。 The second element with id 2 has no name (is null), but has a reference to element 1 ("id_replace"). id 为 2 的第二个元素没有名称(为空),但有对元素 1 的引用(“id_replace”)。 In this case I would like the name returned by item 2 to be "Example" like item 1. And also the "Includes" quote to item 1 references.
在这种情况下,我希望第 2 项返回的名称与第 1 项一样是“示例”。还有对第 1 项引用的“包括”引用。
The reason I have such a strange idea is that I need to have linked the elements, and if element 1 changes, the changes made are displayed on element 2 as well.我之所以有这样一个奇怪的想法,是因为我需要链接元素,如果元素 1 发生变化,所做的变化也会显示在元素 2 上。
Sure you can.你当然可以。 Assuming that your class is:
假设你的 class 是:
public class YourClass
{
public int id { get; set; }
public string name { get; set; }
public int? id_replace { get; set; }
}
In your class, you need to have the one to many referencing properties:在您的 class 中,您需要具有一对多引用属性:
public YourClass parent { get; set; }
public IList<YourClass> children { get; set; }
Then, in your DbContext class, in the override OnModelCreating function, you need to have a relationship set in the fluent API that indicates that id_replace is a self-referencing foreign key:然后,在您的 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);
});
After doing that(and migrating), you have the necessary navigation properties to be able to add computed properties that do not represent anything in the database.这样做(并迁移)之后,您将拥有必要的导航属性,以便能够添加不代表数据库中任何内容的计算属性。 So your class can have the property:
所以你的 class 可以有属性:
public int alt_name => name??$"\"{parent.name}\"";
So eventually, your class will look something like this:所以最终,您的 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}\"";
}
That way, you can discard the name
property and just call on the alt_name
property.这样,您就可以放弃
name
属性,而只调用alt_name
属性。 You can even set the name
property as private or change the names to avoid confusion.您甚至可以将
name
属性设置为私有或更改名称以避免混淆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.