xx77aBs
xx77aBs

Reputation: 4768

Retrieving data from WCF service

Let's say I have database with two tables - Groups and Items.

As you can see, there is one-to-many relation between Groups and Items.

I'm trying to build a web service using WCF and LINQ. I've added new LINQ to SQL classes file, and I've imported these two tables. Visual Studio has automatically generated proper classes for me.

After that, I've create simple client for the service, just to check if everything is working. After I call GetAllGroups() method, I get all groups from Groups table. But their property Items is always null.

So my question is - is there a way to force WCF to return whole class (whole Group class and all Items that belong to it)? Or is this the way it should behave?

EDIT: This is function inside WCF Service that returns all Groups:

    public List<Group> GetAllGroups()
    {
        List<Group> groups = (from r in db.Groups select r).ToList();

        return groups;
    }

I've checked while debugging and every Group object inside GetAllGroups() function has it's items, but after client receives them - every Items property is set to null.

Upvotes: 1

Views: 838

Answers (1)

marc_s
marc_s

Reputation: 754468

Most likely, you're experiencing the default "lazy-loading" behavior of Linq-to-SQL. When you debug and look at the .Items collection - that causes the items to be loaded. This doesn't happen however when your service code runs normally.

You can however enforce "eager-loading" of those items - try something like this: (see Using DataLoadOptions to Control Deferred Loading or LINQ to SQL, Lazy Loading and Prefetching for more details)

public List<Group> GetAllGroups()
{
    // this line should really be where you *instantiate* your "db" context!
    db.DeferredLoadingEnabled = false;

    DataLoadOptions dlo = new DataLoadOptions();
    dlo.LoadWith<Group>(g => g.Items);

    db.LoadOptions = dlo;

    List<Group> groups = (from r in db.Groups select r).ToList();

    return groups;
}

Do you get the Items collection populated now, when you call your service?

Upvotes: 2

Related Questions