簡體   English   中英

使用導航屬性獲取數據

[英]using Navigation property to get Data

我正在使用Entity Framework創建App。我從Database中加載了數據庫模型。在Course表中DepartmentNavigation PropertyDepartmentID是外鍵。我創建了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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM