Jan Hommes
Jan Hommes

Reputation: 5152

Querying data with EF doesn't return all entities

I'am currently changing a project from LINQ to SQL to LINQ to Entity. I have the following entity:

Customer -> Address

I query my database through a WCF Data Service async with this method:

public static async Task<IEnumerable<TResult>> ExecuteAsync<TResult>(this DataServiceQuery<TResult> query)
{
    var queryTask = Task.Factory.FromAsync<IEnumerable<TResult>>(query.BeginExecute(null, null), (asResult) =>
    {
        var result = query.EndExecute(asResult);
        return result;
    });

    return await queryTask;
}

If I do a query on this entity, I can access the Customer, but the address is still null:

var query = (DataServiceQuery<Customer>)client.Customer.OrderBy(session => session.LastName);
var data = await query.ExecuteAsync();
Test2.Text = data.LastName(); //returns the lastname
Test2.Text = data.First().Address.Stret; //Address is Null

I have checked the database and the foreign keys are set correctly. Why is the address null? Do I have to query another way? In LINQ to SQL it was possible to access the related entity, how can I archive this in LINQ to Entity?

Upvotes: 1

Views: 230

Answers (2)

nkvu
nkvu

Reputation: 5841

[nkvu - moving as an answer as indicated by the original poster. Also highly recommend @RAS's answer to this question for an explanation of the different loading strategies.]

Perhaps try to use an [Expand]( http://msdn.microsoft.com/en-us/library/ee358709.aspx) call against Address when constructing your query to load related entities.

Upvotes: 2

RAS
RAS

Reputation: 3385

It all depends on your model. There are three approaches: Explicit Loading, Eager Loading, and Lazy Loading. For eager loading, you have to use Include. Or you want to turn on Lazy loading by specifying Virtual keyword next to your property and set LazyLoadingEnabled = true for your DataContext. See more information on loading of related entities here: http://msdn.microsoft.com/en-us/data/jj574232.aspx

Upvotes: 2

Related Questions