Ranjith Varadan Ranjith Varadan - 1 year ago 53
ASP.NET (C#) Question

Two Tables Two Relationships ASP MVC

I had this doubt this morning and couldn't get an answer. I hope someone can help me.

I have two tables (T1 & T2)

-> Id (P)
-> InstanceId (U)
-> ObjectId (U)
-> Name

-> Id (P)
-> InstanceId (F) (Foreign key for T1.InstanceId)
-> ObjectId (F) (Foreign key for T1.InstanceId)
-> Grade

I need to join these two tables using both the relationships and display the details of both tables using linq.

I have used this linq query but don't know how to return both tables, if i select t1 and t2 from this query, then ObjectId reference is not used (i.e t12)?

How can i solve this. I need to use both the relationships and wants to get both tables values.


var result = from t1 in db.T1
join t2 in db.T2 on t1.InstanceId equals t2.InstanceId
join t12 in db.T2 on t2.ObjectId equals t12.ObjectId
select t1;

Answer Source

You should use new keyword.

join clause

var result =
        from t1 in db.T1
        join t2 in db.T2 on new { ObjectId : t1.ObjectId , InstanceId = t1.InstanceId} equals
                            new { ObjectId : t2.ObjectId , InstanceId = t2.InstanceId}
        select new