简体   繁体   English

实体框架一对多自引用关系

[英]Entity framework one to many self referncing relation

This is my application's model: 这是我的应用程序的模型:

public class Email
{
    public int Id {get; set;}

    public string Content {get; set;}

    public string Address {get; set;}
}

I want to add the option to response to an email (Chain of emails - responses) should it look like this?: 我想添加选项以回复电子邮件(电子邮件链-回复),看起来像这样吗?:

public class Email
{
    public int Id {get; set;}

    public string Content {get; set;}

    public string Address {get; set;}

    public int? PreviousEmailId {get; set;}

    public virtual Email PreviousEmail {get; set;}

    public virtual List<Email> Responses {get; set;}
}

The response email can be a response to another email and so on.. just like an email application 响应电子邮件可以是对另一封电子邮件的响应,依此类推..就像电子邮件应用程序一样

I want to have the possibility to get an email and display all of the emails it is referred to, as a chain, to my clients. 我希望有可能收到一封电子邮件,并将所有被称为链的电子邮件显示给我的客户。 And just like in real Email application, when deleting an email, All of the chain should be deleted as well. 就像在实际的电子邮件应用程序中一样,在删除电子邮件时,所有链也应被删除。

Can anyone tell me how should I define the model (I'm using EF 6 code first). 谁能告诉我如何定义模型(我先使用EF 6代码)。 How should I define the relations? 我应该如何定义关系? What is the best practice? 最佳做法是什么?

I hope it's clear enough, it's similar concept to how other Email application's work. 我希望它很清楚,它与其他电子邮件应用程序的工作原理类似。

Thanks! 谢谢!

You can solve this issue by two ways 您可以通过两种方法解决此问题

first solution: same as you proposed which called a recursive relations "self relation", to store an optional reference to the parent Email "Previous Email" in your case as follow: 第一个解决方案:与您提出的称为递归关系“自我关系”的提议相同,在您的情况下,存储对父电子邮件“上一个电子邮件”的可选引用,如下所示:

public class Email
{
     public int Id {get; set;}
     public int? PrevousEmailId {get; set;}
     // other properties

     public virtual Email PreviousEmail{get;set;}
}

second solution: to store the relation in a separate table that will allow you to response to many recipients at the same time for example and its a general solution of the recursive relation or graph relation ship as follows: 第二种解决方案:将关系存储在单独的表中,这将使您可以同时响应多个收件人,例如,其递归关系或图关系的一般解决方案如下:

public class Email
{
     public int Id {get; set;}
     // other properties
}

public class EmailResponse
{
     public int EmailId {get; set;}
     public int PreviousEmailId {get; set;}

     public virtual Email Email {get; set;}
     public virtual Email PreviousEmail {get; set;}
}

I hope this will help you 我希望这能帮到您

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

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