StevenGodin
StevenGodin

Reputation: 498

How to configure EF to automatically populate child Foreign Key

When a parent class is not using a database generated Identifier how can I configure Entity Framework to automatically populate the Foreign Key in the child object.

Example Model:

public class Parent
{
    [Key]
    public string Name { get; set; }

    public virtual List<Child> Children { get; set; }
}

public class Child
{
    [Key]
    [Column(Order = 1)]
    public string ParentName { get; set; }

    [Key]
    [Column(Order = 2)]
    public string ChildName { get; set; }
}

Example Seed Method:

context.Parents.AddOrUpdate(p => p.Name,
    new Parent
    {
        Name = "Test",
        Children = new List<Child>
        {
            new Child {ParentName = "Test", ChildName = "TestChild"},
            new Child {ParentName = "Test", ChildName = "NewChild"}
        }
    });

Is it possible to configure EF so that I don't have to manually set ParentName = "Test" for each new Child in the Children list?

Edit - Here is the generated migration

CreateTable(
    "dbo.Parents",
    c => new
    {
        Name = c.String(nullable: false, maxLength: 128),
    })
    .PrimaryKey(t => t.Name);

CreateTable(
    "dbo.Children",
    c => new
    {
        ParentName = c.String(nullable: false, maxLength: 128),
        ChildName = c.String(nullable: false, maxLength: 128),
    })
    .PrimaryKey(t => new {t.ParentName, t.ChildName})
    .ForeignKey("dbo.Parents", t => t.ParentName, cascadeDelete: true)
    .Index(t => t.ParentName);

Upvotes: 2

Views: 2469

Answers (1)

bubi
bubi

Reputation: 6501

You can add a navigation property to Child class, configure the model and then everything should work

public class Child
{
    [Key]
    [Column(Order = 1)]
    public string ParentName { get; set; }

    [Key]
    [Column(Order = 2)]
    public string ChildName { get; set; }

    public virtual Parent Parent { get; set; } // <-- Add this
}

This is the configuration

        modelBuilder.Entity<Parent>()
            .HasMany(_ => _.Children)
            .WithRequired(_ => _.Parent)
            .HasForeignKey(_ => _.ParentName);

(without Child.Parent it does not work, quite strange behaviour)

Upvotes: 1

Related Questions