Auto Relationship with Entity Framework 2.2

3

How do I make an Auto Relationship with EF Core 2.2?

I found a link that teaches how to do with EF, but in EF it 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);
    
asked by anonymous 12.12.2018 / 17:44

1 answer

3

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

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

that is, it should tell you what field the primary key refers to and what foreign key the framework will load according to the relation. It really has the difference in the previous version where in the case it is a HasMany(k => k.SubMenu) which is the collection of Menu ( SubMenu ) and in method WithOne you do not 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, make the following code:

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