[英]using Navigation property to get Data
我正在使用Entity Framework創建App。我從Database中加載了數據庫模型。在Course
表中Department
是Navigation Property
, DepartmentID
是外鍵。我創建了gridview並將其數據源設置為Course Table,但是我想要看到Deaptment Name
,而不是department ID
。我可以像使用導航性能Department.count
但我怎么能使用導航屬性從表處獲取數據(部門名稱)。 任何可以幫助我解決此問題的人都是我的密碼
var result = (from o in ctx.Courses.Include("Department")
where o.Title == TextBox2.Text
select o
).First();
//GridView4.DataSourceID="";
GridView3.DataSource=result;
GridView3.DataBind();
如果我不使用First Function,那么我將無法訪問Department Name屬性,如果我使用First()則表示
Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource.
請告訴我我該如何解決?
var result = (from c in dbContext.Course
select c).First();
if(!result.Department.IsLoaded)
{
result.Department.Load(); //this will load the course.Department navigation property
}
//Assuming you have 1 - 1 relationship with course to department
string departmentName = result.Department.Name;
或者,如果您與部門有1-M關系,則:
foreach(Department d in result.Department)
{
Console.WriteLine(d.Name);
}
編輯:
而不是嘗試加載Department,請執行以下操作
if(!result.DepartmentReference.IsLoaded)
{
result.DepartmentReference.Load()
}
我認為羅斯文(Northwind)中的產品和類別表與您的需求相似。 我會這樣寫查詢:
var ctx = new NorthwindEntities();
var query = from prod in ctx.Products
where prod.ProductName.StartsWith("C")
select new { prod.ProductName, prod.UnitPrice, prod.Category.CategoryName };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.