7

My question is similar to this one, but in this case I do have a collection property on the parent referring to the childeren:

public class Parent
{
    public int Id { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public int ParentId { get; set; }
}

And just as with the cited question, I don't want/need a Parent property on Child.

So how should the following syntax be altered to define the relationship?

modelBuilder.Entity<Child>()
    .HasRequired(c => c.Parent)   <---- no such property "Parent"
    .WithMany(p => p.Children)
    .HasForeignKey(c => c.ParentId); 
Community
  • 1
  • 1
BCA
  • 7,776
  • 3
  • 38
  • 53

1 Answers1

12

You can use WithRequired method without parameter:

modelBuilder.Entity<Parent>() 
    .HasMany(p => p.Children)
    .WithRequired()
    .HasForeignKey(c => c.ParentId); 

With part can be left empty if there is no inverse navigation property.

ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • Ah--I didn't realized the association could be defined on the parent's end. This works in practice (EF upholds the relationship when creating, deleting, etc)? – BCA Feb 09 '17 at 14:42
  • Yes, the one to many relationship is going to be created in your DB, so it will uphold the relationship when you do all CRUD operations – ocuenca Feb 09 '17 at 14:56