Click here to Skip to main content
15,908,673 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hello
I want to code a join on one to many relation in Entity Framework and Have access to both table fields but I cant, the join in SQL is :

SQL
SELECT        Letter.Text, Users.UserName, Users.ID
FROM            Letter INNER JOIN
                         Users ON Letter.UserID = Users.ID


but in Entity Framework, I have no access to the field "Text" which is in "Letter" Table.

code for Entity Framework:

C#
_TestEntities.Users.select( c => new JoinTable {c.UserName, c.Letter. Text });


I have no access to "text". and JoinTable is a class:

C#
public partial class JoinTable 
        {
            public int ID{ get; set; }
            public string UserName{ get; set; }
            public partial Letter _Letter{ get; set; }
        }


Thanks in advance

What I have tried:

I have tried code above in EF, But it wont let me access to letter Table Fields such as Text
Posted
Updated 20-Oct-16 5:37am

1 solution

Hi,

Maybe you can try such as:
C#
var data = (from user in _TestEntities.Users
            select new JoinTable
            {
                ID = user.ID,
                UserName = user.UserName,
                Letter = new Letter() 
                    {
                       //not sure about the nested object when projecting but still to get the idea
                       Text = user.Letters.FirstOrDefault().Text
                    }  
            });
//Then iterate results ex
foreach(var row in data
{
  //etc
}


This is referred to as Linq projection, see link Query Expression Syntax Examples: Projection (LINQ to DataSet)[^]
 
Share this answer
 
Comments
Ali Majed HA 20-Oct-16 11:58am    
Hello
Thanks for the solution but it will run with the error : "The entity or complex type 'Test02Model.Letter' cannot be constructed in a LINQ to Entities query."

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900