Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6350885
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T21:53:47+00:00 2026-05-24T21:53:47+00:00

I have a question about One-To-Many relationship between two tables when there is the

  • 0

I have a question about One-To-Many relationship between two tables when there is the link (join) table between.

Example tables:

ChildTable:
ID int NOT NULL PK
Relation int NOT NULL

ParentTable:
ID int NOT NULL PK
Name nvarchar(50) NOT NULL

ParentChildren:
ParentTable_ID int NOT NULL PFK
ChildTable_ID int NOT NULL PFK

Entities:

public class ChildTable
{
    public ChildTable()
    {
        this.ParentTables = new List<ParentTable>();
    }

    public int ID { get; set; }       
    public int Relation { get; set; }
    public virtual ICollection<ParentTable> ParentTables { get; set; }
}

public class ParentTable
{
    public ParentTable()
    {
        this.ChildTables = new List<ChildTable>();
    }

    public int ID { get; set; }   
    public string Name { get; set; }
    public virtual ICollection<ChildTable> ChildTables { get; set; }
}

Mapping:

public class ChildTableMap : EntityTypeConfiguration<ChildTable>
{
    public ChildTableMap()
    {
        // Primary Key
        this.HasKey(t => t.ID);

        // Properties
        // Table & Column Mappings
        this.ToTable("ChildTable");
        this.Property(t => t.ID).HasColumnName("ID");
        this.Property(t => t.Relation).HasColumnName("Relation");
    }
}
public class ParentTableMap : EntityTypeConfiguration<ParentTable>
{
    public ParentTableMap()
    {
        // Primary Key
        this.HasKey(t => t.ID);

        // Properties
        this.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(50);

        // Table & Column Mappings
        this.ToTable("ParentTable");
        this.Property(t => t.ID).HasColumnName("ID");
        this.Property(t => t.Name).HasColumnName("Name");

        // Relationships
        this.HasMany(t => t.ChildTables)
            .WithMany(t => t.ParentTables)
            .Map(m =>
                {
                    m.ToTable("ParentChildren");
                    m.MapLeftKey("ParentTable_ID");
                    m.MapRightKey("ChildTable_ID");
                });

    }
}

Context:

public class TestContext : DbContext
{
    static TestContext()
    { 
        Database.SetInitializer<TestContext>(null);
    }

    public DbSet<ChildTable> ChildTables { get; set; }
    public DbSet<ParentTable> ParentTables { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
        modelBuilder.Configurations.Add(new ChildTableMap());
        modelBuilder.Configurations.Add(new ParentTableMap());
    }
}

Code to add the child and parent:

using (var context = new TestContext())
        {
                var parent = new ParentTable { Name = "Mother Goose" };                   
                var child = new ChildTable { Relation = 1 };                   
                context.ParentTables.Add(parent);
                context.ChildTables.Add(child);
                parent.ChildTables.Add(child);
                context.SaveChanges();
        }

And all works as expected, but I really have only 1 parent and many children.

How to do the mapping that includes writing to the link table (with changed ChildTable class that does not have the ICollection of ParentTable)?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T21:53:48+00:00Added an answer on May 24, 2026 at 9:53 pm

    It’s not possible to define such a mapping. Join tables are only for many-to-many relationships. You have to keep in mind that your database schema (which you cannot change, as you said in the comments to your question) already defines a many-to-many relationship. For example these two entries…

    ParentTable_ID:  1    2
    ChildTable_ID:   1    1
    

    …are valid entries in the ParentChildren table, they don’t violate the PK constraint and they say that child 1 has the two parents 1 and 2.

    If your business logic only allows that a child can have only one single parent, the database schema is modeled wrong. You cannot fix this flaw with EF.

    A possible workaround might be to ensure in your business logic in your code that the ParentTables collection of your ChildTable entity never has more than one element, perhaps by introducing a not mapped helper property:

    public class ChildTable
    {
        public ChildTable()
        {
            this.ParentTables = new List<ParentTable>();
        }
    
        public int ID { get; set; }       
        public int Relation { get; set; }
        public virtual ICollection<ParentTable> ParentTables { get; set; }
    
        [NotMapped] // or use .Ignore(c => c.ParentTable) in Fluent API
        public ParentTable ParentTable
        {
            get
            {
                return ParentTables.SingleOrDefault();
                // let is crash if there is more than one element in the list
            }
    
            set
            {
                var oldParent = ParentTables.SingleOrDefault();
                if (oldParent != value)
                {
                    ParentTables.Clear();
                    if (value != null)
                        ParentTables.Add(value);
                }
            }
        }
    }
    

    It’s only a little help if you only use the ParentTable property. You have to avoid to use the collection and add more than one parent. You cannot make it private because it must be mapped. It’s also not safe on the other side of the relationship. You could write: parent1.ChildTables.Add(child1); parent2.ChildTables.Add(child1); which would lead to two parents for child1 in the database. You could catch this by writing helper methods for adding a child on the ParentTable entity which check if the added child doesn’t already have a parent other than this parent.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a question about Criteria method, one-to-many relation to the database, 'one' is
I have a question about Database design. I have two tables, usertable and historytable,
I have a pretty newb question, about a many-to-many relationship I've created, and pulling
I have a question about best practices regarding how one should approach storing complex
I have a question about this question . I posted a reply there but
I have a question about object relational updates on join fields. I am working
I have seen people often use a separate table to store relations between tables.
I have question about NSView: Imagine a Custom View where the mouseDown, mouseDrag and
I have question about normalization. Suppose I have an applications dealing with songs. First
I have a question about using streams in .NET to load files from disk.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.