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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T21:14:09+00:00 2026-05-18T21:14:09+00:00

When using the CTP 5 of Entity Framework code-first library (as announced here )

  • 0

When using the CTP 5 of Entity Framework code-first library (as announced here) I’m trying to create a class that maps to a very simple hierarchy table.

Here’s the SQL that builds the table:

CREATE TABLE [dbo].[People]
(
 Id  uniqueidentifier not null primary key rowguidcol,
 Name  nvarchar(50) not null,
 Parent  uniqueidentifier null
)
ALTER TABLE [dbo].[People]
 ADD CONSTRAINT [ParentOfPerson] 
 FOREIGN KEY (Parent)
 REFERENCES People (Id)

Here’s the code that I would hope to have automatically mapped back to that table:

class Person
{
    public Guid Id { get; set; }
    public String Name { get; set; }
    public virtual Person Parent { get; set; }
    public virtual ICollection<Person> Children { get; set; }
}

class FamilyContext : DbContext
{
    public DbSet<Person> People { get; set; }
}

I have the connectionstring setup in the app.config file as so:

<configuration>
  <connectionStrings>
    <add name="FamilyContext" connectionString="server=(local); database=CodeFirstTrial; trusted_connection=true" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

And finally I’m trying to use the class to add a parent and a child entity like this:

static void Main(string[] args)
{
    using (FamilyContext context = new FamilyContext())
    {
        var fred = new Person
        {
            Id = Guid.NewGuid(),
            Name = "Fred"
        };
        var pebbles = new Person
        {
            Id = Guid.NewGuid(),
            Name = "Pebbles",
            Parent = fred
        };
        context.People.Add(fred);
        var rowCount = context.SaveChanges();
        Console.WriteLine("rows added: {0}", rowCount);
        var population = from p in context.People select new { p.Name };
        foreach (var person in population)
            Console.WriteLine(person);
    }
}

There is clearly something missing here. The exception that I get is:

Invalid column name ‘PersonId’.

I understand the value of convention over configuration, and my team and I are thrilled at the prospect of ditching the edmx / designer nightmare — but there doesn’t seem to be a clear document on what the convention is. (We just lucked into the notion of plural table names, for singular class names)

Some guidance on how to make this very simple example fall into place would be appreciated.

UPDATE:
Changing the column name in the People table from Parent to PersonId allows the Add of fred to proceed. Howerver you’ll notice that pebbles is a added to the Children collection of fred and so I would have expected pebbles to be added to the database as well when Fred was added, but such was not the case. This is very simple model, so I’m more than a bit discouraged that there should be this much guess work involved in getting a couple rows into a database.

  • 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-18T21:14:10+00:00Added an answer on May 18, 2026 at 9:14 pm

    You need to drop down to fluent API to achieve your desired schema (Data annotations wouldn’t do it). Precisely you have an Independent One-to-Many Self Reference Association that also has a custom name for the foreign key column (People.Parent). Here is how it supposed to get done with EF Code First:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
                    .HasOptional(p => p.Parent)
                    .WithMany(p => p.Children)
                    .IsIndependent()
                    .Map(m => m.MapKey(p => p.Id, "ParentID"));
    }
    

    However, this throws an InvalidOperationException with this message Sequence contains more than one matching element. which sounds to be a CTP5 bug as per the link Steven mentioned in his answer.

    You can use a workaround until this bug get fixed in the RTM and that is to accept the default name for the FK column which is PersonID. For this you need to change your schema a little bit:

    CREATE TABLE [dbo].[People]
    (
         Id  uniqueidentifier not null primary key rowguidcol,
         Name  nvarchar(50) not null,
         PersonId  uniqueidentifier null
    )
    ALTER TABLE [dbo].[People] ADD CONSTRAINT [ParentOfPerson] 
    FOREIGN KEY (PersonId) REFERENCES People (Id)
    GO
    ALTER TABLE [dbo].[People] CHECK CONSTRAINT [ParentOfPerson]
    GO
    

    And then using this fluent API will match your data model to the DB Schema:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
                    .HasOptional(p => p.Parent)
                    .WithMany(p => p.Children)
                    .IsIndependent();
    }
    

    Add a new Parent record containing a Child:

    using (FamilyContext context = new FamilyContext())
    {
        var pebbles = new Person
        {
            Id = Guid.NewGuid(),
            Name = "Pebbles",                    
        };
        var fred = new Person
        {
            Id = Guid.NewGuid(),
            Name = "Fred",
            Children = new List<Person>() 
            { 
                pebbles
            }
        };                
        context.People.Add(fred);               
        context.SaveChanges();                                
    }
    

    Add a new Child record containing a Parent:

    using (FamilyContext context = new FamilyContext())
    {
        var fred = new Person
        {
            Id = Guid.NewGuid(),
            Name = "Fred",                
        };
        var pebbles = new Person
        {
            Id = Guid.NewGuid(),
            Name = "Pebbles",
            Parent = fred
        };
        context.People.Add(pebbles);
        var rowCount = context.SaveChanges();                                
    }
    

    Both codes has the same effect and that is adding a new parent (Fred) with a child (Pebbles).

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

Sidebar

Related Questions

In Microsoft Oslo SDK CTP 2008 (using Intellipad) the following code compiles fine: module
Is there any recommendation against using this CTP? Is it unstable?
Using ASP.NET MVC there are situations (such as form submission) that may require a
Using C# .NET 3.5 and WCF, I'm trying to write out some of the
Using TortoiseSVN against VisualSVN I delete a source file that I should not have
Using online interfaces to a version control system is a nice way to have
Using PyObjC , you can use Python to write Cocoa applications for OS X.
Using C# and System.Data.SqlClient, is there a way to retrieve a list of parameters
Using VS2008, C#, .Net 2 and Winforms how can I make a regular Button
Using JDeveloper , I started developing a set of web pages for a project

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.