Home >Backend Development >C++ >How to Implement a Many-to-Many Relationship with Additional Properties in EF Core?

How to Implement a Many-to-Many Relationship with Additional Properties in EF Core?

Linda Hamilton
Linda HamiltonOriginal
2025-01-31 10:51:10938browse

How to Implement a Many-to-Many Relationship with Additional Properties in EF Core?

Use the associated table in EF Core to create a multi -to -many relationship

Scene

Suppose we have the following data model:

Configure associated with Fluent API
<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>

Unfortunately, the Entity Framework Core (EF Core) does not support the use of a custom connection table to create a multi -to -multiple relationship. EF Core automatically creates and manages the internal connection table to make it unable to access.

Alternative: Create two pairs of multi -relationships

To use a connection table with additional attributes (such as

), we need to establish two one -to -multi -relationship:

MemberComment (The code segment is the same as input, the duplicate here is omitted)

Use association

Now, we can perform various operations on these entities:

Get the member's comment

    Get the members with comments
  • Filter the attribute in the connection table
  • Create and manage the relationship between entities
  • Delete relationship and entity
  • Query
Relations management

The above is the detailed content of How to Implement a Many-to-Many Relationship with Additional Properties in EF Core?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn