0

Is it possible to do the following mapping with the Entity Framework Code First?

public class Parent
{
     [Key]
     public int ID {get; set;}
     public string statecode{get; set;}

     public virtual ICollection<Child> children{get; set;}
}

public class Child
{
    [Key, Column(Order = 0)]
    public string StateFromCode { get; set; }
    [Key, Column(Order = 1)]
    public string StateToCode { get; set; }
}

I would like to specify a relation in my dbcontext where children are lazy loaded into the Parent and Parent.statecode == Child.StateToCode. Note that StateToCode is part of the Child key and not the entire primary key. What should I specify in my DB context below to make this happen if possible at all?

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<Parent>().HasMany(x=>x.children)..............

    }

1 Answer 1

2

It is not possible - especially not with code first where relations must follow exactly same rules as specifying referential constraint in the database. So the only valid relation will require Parent's Id column in Child table and foreign constraint on this column

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for you answer. I ended up populating children collection manually as 'p.children = dbcontext.Children.where(c=>c.StateToCode == p.statecode)' and changed the collection from ICollection<child> to [NotMapped] IEnumerable<child>.
Is this still the case, or has the newer version made this functionality available?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.