Querying on field of one-to-many relationship

Posts   
 
    
AlexWalker
User
Posts: 40
Joined: 05-Nov-2008
# Posted on: 05-Oct-2009 17:22:18   

I want to find all contracts whose contract data's model number is equal to a certain value. There is a one-to-many relationship between contract and contract data.

I'm trying to do this:

using (DataAccessAdapter adapter = new DataAccessAdapter())
{
    LinqMetaData metaData = new LinqMetaData(adapter);
     var q = (from c in metaData.Contract
                         select c)
                  .WithPath(p => p.Prefetch(cm => cm.ContractData));

    if (!string.IsNullOrEmpty(model))
    {
        q = q.Where(all => all. ContractData.Where(data => data .Model== modelNumber) != null);
    }

    foreach (ContractEntity c in q)
    {
        foundItems.Add(c);
    }
}

I'm getting a null reference exception at the foreach loop.

How can I query using a field value of the many side of a one-to-many relationship?

AlexWalker
User
Posts: 40
Joined: 05-Nov-2008
# Posted on: 05-Oct-2009 20:28:31   

I was able to do a JOIN to get the data I needed, but I'm still wondering if there's a more concise way.

if (!string.IsNullOrEmpty(modelNumber))
{
    var data = from d in metaData.ContractData
                      where d.ModelNumber == modelNumber
                       select d;

    q = q.Join<ContractMasterEntity, ContractDetailEntity, string, ContractMasterEntity>(
              data ,
              cm => cm.ContractNumber,
              d => d.ContractNumber,
              (cm, d) => cm);
}
daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 06-Oct-2009 05:25:53   

The join is ok. You also could filter on count but I think the join is ok. You can write the join directly in the linq query.

David Elizondo | LLBLGen Support Team