Eager loading support for Microsoft.Datasync.Client when querying remote table

75 Views Asked by At

I am looking for how to use the 'Include' method to specify related data for the EntityTableData or DataSyncClientData objects in the Microsoft.Datasync library. I would like to achieve something like below:

var data = await _remotetable
                  .Include(x => x.ParentTable)
                  .ToListAsync();

           

How do I achieve that?

1

There are 1 best solutions below

0
Balaji On

Below are the steps I followed:

  • ADbContext class is defined that inherits from DbContext. It consists of DB set properties for two tables NewTable and ParentTable.

  • NewTable has navigation property ParentTable representing a relation between the two tables.

  • Relationship is determined by the ParentTableId foreign key property in NewTable.

  • I used Entity Framework core to query the NewTable with .Include method. It loads related ParentTable entities.

Code I tried with:

public class ADbContext : DbContext
{
    public DbSet<NewTable> NewTable { get; set; }
    public DbSet<ParentTable> ParentTable { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("*****");
    }
}

static async Task Main()
{
    try
    {
        using var context = new ADbContext();

        var data = await context.NewTable
            .Include(x => x.ParentTable)
            .ToListAsync();

        foreach (var item in data)
        {
            Console.WriteLine("NewTable Id: {item.Id}, Name: {item.Name}, Age: {item.Age}, ParentTableId: {item.ParentTableId}");
            Console.WriteLine($"ParentTable Id: {item.ParentTable.Id}, ParentName: {item.ParentTable.FirstName}, " +
                "ParentAge: {item.ParentTable.Age}");
            Console.WriteLine();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}

Output:

NewTable Id: 1, Name: Suresh, Age: 30, ParentTableId: 2
ParentTable Id: 2, ParentName: Sai, ParentAge: 26

NewTable Id: 2, Name: Sampath, Age: 35, ParentTableId: 3
ParentTable Id: 3, ParentName: Yeggi, ParentAge: 54

NewTable Id: 3, Name: Sanjeev, Age: 40, ParentTableId: 1
ParentTable Id: 1, ParentName: Pavan, ParentAge: 25