Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First foreign key without navigation property, but with parent collection property

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); 
like image 399
BCA Avatar asked Feb 08 '17 17:02

BCA


People also ask

How do you use a foreign key in code first approach?

To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship.

How do you add a foreign key to EF?

The ForeignKey attribute is used to configure a foreign key in the relationship between two entities in EF 6 and EF Core. It overrides the default conventions. As per the default convention, EF makes a property as foreign key property when its name matches with the primary key property of a related entity.


1 Answers

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.

like image 121
octavioccl Avatar answered Sep 30 '22 17:09

octavioccl