views:

87

answers:

1

Hello,

Let's say I have two tables (Address and Phone) in sql which have one-to-one relationship. I have created corresponding linq to sql classes and changed the association to OneToOne

I want to retrieve both objects by filtering child object. e.g I have the following query which works fine:

var n = db.Addresses.Where(t => t.Phone.Number == 100);

Is there any way I can make the following work:

var n = db.Addresses.Where(t => t.Phone == new Phone(100));

The Phone class constructor above initializes the Number property. As I can see the query that is issued contains a clause which filters Phones table by id (primary key) but the number clause in not included.

If I set Number as primary key in visual studio then it is included in the where clause but the search still does not return anything as the parameter value for id is 0. Even if it worked it is not a solution as Number should not be a primary key.

+1  A: 

What you're asking doesn't quite make sense. If you want the phone element given the address, you have this by accessing the Address.Phone property.

You can't initialise a type and use that to project on as this is DLinq, where the query is translated down to the DB. You can do this on Linq to objects, but it would force you to enumerate your list, which would fetch all the database information into memory, which may not be good for performance...

I don't see the issue here? You have the address, a working search for it, and you can access the phone property by accessing the Address property.

Spence
I am just interested if it is possible to make the second query work in the same way as the first one works.As I understand it is not possible. Am I correct?
Giorgi
Correct. What Linq to SQL is doing is creating an "Expression tree" which kind of looks like the query, (for each address, check the phone property, if it's equal to 100 then return it), and then transforms this into an SQL query. It doesn't make sense to feed a new object to your query as it can't be logically transformed into SQL. You could however fetch all addresses, and then do this to the query but it would affect performance.
Spence
Thanks for the answer
Giorgi