EF Code The first foreign key without a navigation property, but with a parent property

My question is similar to this one, but in this case I have a collection property on the parent that references 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 this question, I don't need / need the Parent property on Child .

So how do you change the following syntax to define a relationship?

 modelBuilder.Entity<Child>() .HasRequired(c => c.Parent) <---- no such property "Parent" .WithMany(p => p.Children) .HasForeignKey(c => c.ParentId); 
+6
source share
1 answer

You can use the WithRequired method without a parameter:

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

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

+6
source

Source: https://habr.com/ru/post/1014809/


All Articles