EntityDataSource query inner join

2019-07-15 09:44发布

问题:

I have a DB with 3 tables:

User{UserId,UserName}
Role{RoleId,RoleName}
User_Role{UserId,RoleId}

This query:

int userIdPassByUrl = 0;
MyDbContext ctx = new MyDbContext();
var query = (from role in ctx.Role
        join userRole in ctx.User_Role on role.RoleId equals userRole.RoleId
        where userRole.UserId == userIdPassByUrl
        select new { role.RoleId, role.RoleName }).Distinct();

I need to show the result of the above query in a Gridview with an EntityDataSource, either code or set it in the design mode.

this is my EntitydataSource:

<asp:EntityDataSource ID="EdsRolesByUser" runat="server" 
        ConnectionString="name=myDbEntities"
        DefaultContainerName="myDbEntities" EnableFlattening="False"
        EntitySetName="Roles" EntityTypeFilter="Role"
        Select="it.[RoleId], it.[RoleName]">
    </asp:EntityDataSource>

Any help would be appreciated, thanks.

回答1:

Finally got it. Have to modified the EntityDataSource removing the EntitySetName and EntityTypeFilter attributes, and add the CommandText like this:

CommandText="SELECT DISTINCT userRole.RoleId, role.RoleName FROM Role AS role
INNER JOIN User_Role as userRole
ON role.RoleId = userRole.RoleId
WHERE userRole.UserId = @UserIdPassbyUrl"

This link help me: http://msdn.microsoft.com/en-us/library/aa697427(v=vs.80).aspx