how to annotate a parent-child relationship with Code-First
Asked Answered
H

4

19

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.

Holle answered 16/12, 2010 at 14:27 Comment(0)
O
16

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).

Opec answered 16/12, 2010 at 20:11 Comment(4)
That's a great answer. Thanks. Now in the code of the OP I was not adding pebbles to the context explicitly, but assuming that she would be added to the database by virtue of her being connected to Fred (by setting her Parent property to the fred instance) That didn't work, but rather I had to add pebbles explicitly. Do you Is that expected behavior?Holle
In this sample code we declare the Children property as ICollection<Person> yet we never instantiate it. Should there be a default constructor to do that?Holle
No problem, see my updated answer for your first question. Also, you don't have to initialize Children in the class constructor specially that you mark it as virtual, but it is still recommended so that you won't hit a NullReferenceException by any chance.Opec
Thanks for the update, shame I can't upvote your answer again.Holle
T
2

In Entity Framework 6 you can do it like this, note public Guid? ParentId { get; set; }. The foreign key MUST be nullable for it to work.

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

https://mcmap.net/q/159330/-entity-framework-code-first-null-foreign-key

Takishatakken answered 15/8, 2018 at 11:43 Comment(0)
M
0

It should work using a mapping like below:

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

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Person>().HasMany(x => x.Children).WithMany().Map(y =>
            {
                y.MapLeftKey((x => x.Id), "ParentID");
                y.MapRightKey((x => x.Id), "ChildID");

            });
    }
}

However that throws an exception: Sequence contains more than one matching element. Apperently that is a bug.

See this thread and the answer to @shichao question: http://blogs.msdn.com/b/adonet/archive/2010/12/06/ef-feature-ctp5-fluent-api-samples.aspx#10102970

Middendorf answered 16/12, 2010 at 18:50 Comment(1)
This fluent API code is for Many-To-Many associations using a join table while the question is about a One-to-Many Self Reference Association. Thanks.Opec
N
0
    class Person
{ 
    [key()]
    public Guid Id { get; set; }
    public String Name { get; set; }
    [ForeignKey("Children")]
    public int? PersonId {get; set;} //Add ForeignKey
    public virtual Person Parent { get; set; }
    public virtual ICollection<Person> Children { get; set; }
}

builder.Entity<Menu>().HasMany(m => m.Children)
                        .WithOne(m => m.Parent)
                        .HasForeignKey(m => m.PersonId);
Noisemaker answered 28/11, 2019 at 0:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.