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 6618013
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T20:46:27+00:00 2026-05-25T20:46:27+00:00

I’m trying to make a one to many self reference using EF4.1 code first.

  • 0

I’m trying to make a one to many self reference using EF4.1 code first. My entity looks like this

public class Site
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Sitename { get; set; }

    public virtual Site ChildSite { get; set; }
    public virtual ICollection<Site> ChildSites { get; set; }
}

And in my context class I do this to make the self reference

modelBuilder.Entity<Site>()
    .HasOptional(s => s.ChildSite)
    .WithMany(s => s.ChildSites)
    .HasForeignKey(s => s.ParentId);

But when i try to add some dummy data to my database with this code

var sites = new List<Site>
{
    new Site { ParentId = 0, Sitename = "Top 1" },
    new Site { ParentId = 0, Sitename = "Top 2" },
    new Site { ParentId = 0, Sitename = "Top 3" },
    new Site { ParentId = 0, Sitename = "Top 4" },
    new Site { ParentId = 1, Sitename = "Sub 1_5" },
    new Site { ParentId = 1, Sitename = "Sub 1_6" },
    new Site { ParentId = 1, Sitename = "Sub 1_7" },
    new Site { ParentId = 1, Sitename = "Sub 1_8" },
    new Site { ParentId = 2, Sitename = "Sub 2_9" },
    new Site { ParentId = 2, Sitename = "Sub 2_10" },
    new Site { ParentId = 2, Sitename = "Sub 2_11" },
    new Site { ParentId = 2, Sitename = "Sub 2_12" },
    new Site { ParentId = 3, Sitename = "Sub 3_13" },
    new Site { ParentId = 3, Sitename = "Sub 3_14" },
    new Site { ParentId = 3, Sitename = "Sub 3_15" },
    new Site { ParentId = 3, Sitename = "Sub 3_16" },
    new Site { ParentId = 4, Sitename = "Sub 4_17" },
    new Site { ParentId = 4, Sitename = "Sub 4_18" },
    new Site { ParentId = 4, Sitename = "Sub 4_19" },
    new Site { ParentId = 4, Sitename = "Sub 4_20" }
};
sites.ForEach(s => context.Sites.Add(s));
context.SaveChanges();

I get this error :

Unable to determine the principal end of the
‘Cms.Model.Site_ChildSite’ relationship. Multiple added entities may
have the same primary key.

What am i missing here ?

Edit :

Here is the solution to my problem. I removed the public virtual Site ChildSite { get; set; } from the entity

public class Site
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Sitename { get; set; }

    public virtual ICollection<Site> ChildSites { get; set; }
}

I then changed the modelBuilder to this

modelBuilder.Entity<Site>()
    .HasMany(s => s.ChildSites)
    .WithOptional()
    .HasForeignKey(s => s.ParentId);

As it seems that auto generation of the database did not work I went ahead and created the table myself like this

int Id, not null, primary key
int ParentId, null
string Sitename, null

And everything works as I want it to.

2nd Edit

And the final step to get the auto generation of dummy data to work

var parent1 = new Site
{
    Sitename = "Top 1",
    ChildSites = new List<Site>
        {
            new Site {Sitename = "Sub 1_5"},
            new Site {Sitename = "Sub 1_6"},
            new Site {Sitename = "Sub 1_7"},
            new Site {Sitename = "Sub 1_8"}
        }
};

ect . . . 

context.Sites.Add(parent1);
context.SaveChanges();

See Slauma answer below

  • 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-25T20:46:27+00:00Added an answer on May 25, 2026 at 8:46 pm

    Your mapping is correct and you don’t need to remove the ChildSite property. You just can’t use foreign key properties when you create your entities and “guess” how those autogenerated numbers will be after the entities are stored and use these numbers in the same entities which are being stored.

    The following instead should work and create the expected rows in the database:

    var parent1 = new Site
    {
        Sitename = "Top 1",
        ChildSites = new List<Site>
            {
                new Site {Sitename = "Sub 1_5"},
                new Site {Sitename = "Sub 1_6"},
                new Site {Sitename = "Sub 1_7"},
                new Site {Sitename = "Sub 1_8"}
            }
    };
    var parent2 = new Site
    {
        Sitename = "Top 2",
        ChildSites = new List<Site>
            {
                new Site {Sitename = "Sub 2_9"},
                new Site {Sitename = "Sub 2_10"},
                new Site {Sitename = "Sub 2_11"},
                new Site {Sitename = "Sub 2_12"}
            }
    };
    var parent3 = new Site
    {
        Sitename = "Top 3",
        ChildSites = new List<Site>
            {
                new Site {Sitename = "Sub 3_13"},
                new Site {Sitename = "Sub 3_14"},
                new Site {Sitename = "Sub 3_15"},
                new Site {Sitename = "Sub 3_16"}
            }
    };
    var parent4 = new Site
    {
        Sitename = "Top 4",
        ChildSites = new List<Site>
            {
                new Site {Sitename = "Sub 4_17"},
                new Site {Sitename = "Sub 4_18"},
                new Site {Sitename = "Sub 4_19"},
                new Site {Sitename = "Sub 4_20"}
            }
    };
    context.Sites.Add(parent1);
    context.Sites.Add(parent2);
    context.Sites.Add(parent3);
    context.Sites.Add(parent4);
    context.SaveChanges();
    

    Edit

    If the entities represented by a foreign key exists in the DB you can use it – for example:

    var site = context.Sites.Single(s => s.Sitename == "Top 1");
    site.ParentId = 4; // set a parent for "Top 1"
    context.SaveChanges();
    

    Add a new child:

    var site = context.Sites.Single(s => s.Sitename == "Top 1");
    site.ChildSites.Add(new Site { Sitename = "Sub 1_9" });
    context.SaveChanges();
    

    Remove a child:

    var site = context.Sites.Single(s => s.Sitename == "Top 1");
    // works because of lazy loading
    var childToRemove = site.ChildSites.Single(s => s.Sitename == "Sub 1_9");
    site.ChildSites.Remove(childToRemove);
    context.SaveChanges();
    

    etc.

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

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I am trying to loop through a bunch of documents I have to put
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has

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.