Home >Backend Development >C++ >How to Implement Many-to-Many Relationships with Custom Join Tables in Entity Framework?
Create multiple -to -many relationships with a custom connection table
In the physical framework, most of the relationships usually involve a hidden connection table of an internal management. However, in some cases, you may need a custom connection table with additional attributes.
The limitations of more relationships
Unfortunately, the use of Fluent API cannot create a multi -pair relationship with a custom connection table. EF requires a hidden, internal management connection table to achieve multiple relationships.
Alternative method
On the contrary, to use a custom connection table with additional attributes, you can create two separate one -to -multi -relationships, each entity to one of the connection table. Example
Consider the following scene:
In this model,
is used as a custom connection table with additional attributesand
.<code class="language-csharp">public class Member { public int MemberID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual ICollection<MemberComment> MemberComments { get; set; } } public class Comment { public int CommentID { get; set; } public string Message { get; set; } public virtual ICollection<MemberComment> MemberComments { get; set; } } public class MemberComment { [Key, Column(Order = 0)] public int MemberID { get; set; } [Key, Column(Order = 1)] public int CommentID { get; set; } public virtual Member Member { get; set; } public virtual Comment Comment { get; set; } public int Something { get; set; } public string SomethingElse { get; set; } }</code>
Inquiry relationship MemberComment
Something
SomethingElse
To query these relationships, you can use Linq expression:
The advantages of this method
This alternative method has the following advantages:
<code class="language-csharp">// 查找 LastName = "Smith" 的成员的所有评论 var commentsOfMembers = context.Members .Where(m => m.LastName == "Smith") .SelectMany(m => m.MemberComments.Select(mc => mc.Comment)) .ToList();</code>
<code class="language-csharp">// 查找 LastName = "Smith" 的所有成员及其评论 var membersWithComments = context.Members .Where(m => m.LastName == "Smith") .Select(m => new { Member = m, Comments = m.MemberComments.Select(mc => mc.Comment) }) .ToList();</code>
Custom connection table: You can control the design of the connection table and add other attributes as needed.
Inquiry:You can screen and connect according to the attributes in the connection table.
The above is the detailed content of How to Implement Many-to-Many Relationships with Custom Join Tables in Entity Framework?. For more information, please follow other related articles on the PHP Chinese website!