带JOIN的EntityDataSource?

时间:2013-05-28 20:29:49

标签: c# asp.net entity-framework entitydatasource

我将GridView绑定到以下EntityDataSource:

<asp:EntityDataSource ID="sessionQuery" runat="server" 
    ConnectionString="name=encoreEntities" DefaultContainerName="encoreEntities"
    EnableFlattening="False" EntitySetName="sessions" Include="user, user.person" 
    Where="it.lastactivity > @NowMinusXMins" OrderBy="it.lastactivity desc" >   
    <WhereParameters>
        <asp:Parameter Name="NowMinusXMins" Type="DateTime" />
    </WhereParameters>
</asp:EntityDataSource>

这很好用。

我有一个名为SessionHistory的表,它有一个外键进入Session。此表记录会话期间访问的页面。我想将Session实体链接到SessionHistory中的最新记录,并在GridView中显示该页面。

联接将是这样的:

从会话中选择* 其中s.sessionid =(通过lastactivitydate desc从sessionhistory顺序中选择前1个sessionid)

我可以像在这篇文章中那样做:EntityDataSource query inner join 但是,我试图保留EF关系,以便我可以在我的Gridview中引用它们(例如session.user.username,session.user.person.lastname等)

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:0)

以下是一个真实示例,其中两个表三个导航属性

<强>表格

  • lm_m_location_type 表定义了一个位置(国家,城市,州等)
  • lm_m_location 表包含排列在父/子层级中的位置的行(例如美国 - &gt;佛罗里达 - &gt;坦帕,奥兰多,迈阿密)

<强>关系

  • lm_m_location_type 定义零对多位置
  • lm_m_location 可以包含零对多子位置
  • lm_m_location 可以包含零个或一个父级位置

导航属性(来自EntityFramework,通过编辑XML)

  • NavigationProperty Name = ChildLocations Relationship = DB.fk_child_loc FromRole = lm_m_location ToRole = lm_m_location1

  • NavigationProperty Name = ParentLocation Relationship = DB.fk_parent_loc FromRole = lm_m_location1 ToRole = lm_m_location

  • NavigationProperty Name = LocationType Relationship = DB.fk_loc_type FromRole = lm_m_location ToRole = lm_m_location_type

代码示例:用于访问位置并包含父行,子行和位置类型行。

//
// code from the controller
//

public ActionResult getLocation()
{
    var lm_m_location = db.lm_m_location
        .Include("ParentLocation")
        .Include("ChildLocations")
        .Include("LocationType")
        .Where(t => t.parent_location_id == LinkDB.MvcApplication.Location.Current.id);

    return View(lm_m_location.ToList());
}

//
// code from the view that accesses each of the included tables
//
@model IEnumerable<LinkDBuilder.Models.lm_m_location>

@Html.DisplayFor(modelItem => item.description)
@Html.DisplayFor(modelItem => item.ParentLocation.description)
@Html.DisplayFor(modelItem => item.LocationType.description)

    // inside a loop of the child locations
    @Html.DisplayFor(modelItem => item.ChildLocations.description)

    // just to show we could drill back to the grand parent location if we wanted
    // of course we would make sure there was a value first in production code
    @Html.DisplayFor(modelItem => item.ParentLocation.ParentLocation.description)