![](/img/trans.png)
[英]Entity Framework with Include statement to select 3rd level specific fields
[英]include 3rd level related collection and display in gridview with code-first entity framework
我的gridview中有以下模板字段(ItemType屬性設置正確: ItemType="gEchoLu.Model.DiscussionTimeframe"
):
<asp:TemplateField HeaderText="Discussion Wall">
<ItemTemplate>
<asp:Label runat="server" ID="lbl_Discussion" Text="<%#Item.DiscussionWall.WallTitle %>"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Course">
<ItemTemplate>
<asp:Label runat="server" ID="lbl_Discussion" Text="<%#Item.DiscussionWall.Course.CourseTitle %>"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
第一個字段顯示正確。 但是,第二個模板字段始終為空。 這是將數據綁定到gridview的代碼:
gEchoLuDBContext db = new gEchoLuDBContext();
var timeframes = db.Timeframes.Include(c => c.DiscussionWall.Course).Where(tf => tf.CreatedBy == userid).ToList();
grd_Timeframes.DataSource = timeframes;
grd_Timeframes.DataBind();
當我調試它時,Course的屬性實際上為空。 在我的模型中,每個TimeFrame
屬於一個DiscussionWall
,而每個DiscussionWall
屬於Course
。 但是, TimeFrame
和Course
之間沒有直接關系。 我不確定在這種情況下我想要的是否可行。 我是否必須在TimeFrame
和DiscussionWall
實體之間定義(一對多)關系才能實現我想要的? (我知道可以使用OnDataBound
完成此操作,但我想知道ItemType
可以用於快速處理此問題)。
這是我模型的相關部分:
public class DiscussionWall
{
[Key]
public int WallId { get; set; }
[Required]
[StringLength(200)]
public string WallTitle { get; set; }
[Required]
[ForeignKey("Course")]
public int CourseId { get; set; }
private Course _course;
public Course Course
{
get { return _course?? (_course = new Course());}
set { _course = value; }
}
public List<DiscussionTimeframe> Timeframes { get; set; }
}
public class DiscussionTimeframe
{
public int DiscussionTimeframeId { get; set; }
[Required]
public string TimeFrameName { get; set; }
public int DiscussionWallId { get; set; }
[ForeignKey("DiscussionWallId")]
public DiscussionWall DiscussionWall { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseTitle { get; set; }
public List<DiscussionWall> DiscussionWalls { get; set; }
}
當我更改此設置時,它起作用了:
private Course _course;
public Course Course
{
get { return _course?? (_course = new Course());}
set { _course = value; }
}
到這個:
public Course Course
{
get;
set;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.