Self Relationship with Entity Framework 2.2

Asked

Viewed 385 times

3

How to Make a Self Relationship with EF Core 2.2?

I found a link that teaches to do with EF, but in EF does not have the Withoptional method.

public class Menu
{
    public int Id { get; set; }
    public string Title { get; set; }

    public int? MenuId { get; set; }        
    public ICollection<Menu> SubMenu { get; set; }
 }

 modelBuilder.Entity<Menu>()
        .HasMany(x => x.SubMenu)
        .WithOptional()
        .HasForeignKey(x => x.MenuId);

    base.OnModelCreating(modelBuilder);

1 answer

5


The auto relationship setting is as follows for your class Menu:

x.HasMany(k => k.SubMenu)
            .WithOne()
            .HasForeignKey(k => k.MenuId)
            .HasPrincipalKey(k => k.Id);

that is, it must inform which field the primary key refers to and which foreign key the framework will click according to the relation. There is actually the difference in the previous version where in the case is a HasMany(k => k.SubMenu) which is the collection of Menu (SubMenu) and in the method WithOne don’t need to report anything.

Complete:

modelBuilder.Entity<Menu>(x =>
        {
            x.ToTable("Menus");

            x.HasKey(k => k.Id);
            x.Property(k => k.Id)
                .UseSqlServerIdentityColumn();

            x.Property(k => k.Title)
                .HasMaxLength(50);

            x.Property(k => k.MenuId);

            x.HasMany(k => k.SubMenu)
                .WithOne()
                .HasForeignKey(k => k.MenuId)
                .HasPrincipalKey(k => k.Id);

        });

To load menu and submenu do the following code:

using (DbContextDatabase t = new DbContextDatabase())
{
     var m0 = t.Menu
            .Where(x => x.MenuId == null)
            .Include(x => x.SubMenu)
            .ToList();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.