【问题标题】:using Navigation property to get Data使用导航属性获取数据
【发布时间】:2012-05-24 03:09:18
【问题描述】:

我正在使用实体框架创建应用程序。我已经从 Database.here 加载了数据库模型在Course 表中DepartmentNavigation PropertyDepartmentID 是外键。我创建了一个网格视图和将其数据源设置为课程表,但我想查看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 函数,那么我无法访问 Department Name 属性,如果我使用 First() 则说明

Data source is an invalid type.  It must be either an IListSource, IEnumerable, or IDataSource.

请告诉我如何解决?

【问题讨论】:

    标签: c# asp.net linq entity-framework navigation-properties


    【解决方案1】:
    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);
    }
    

    编辑:
    不要尝试加载部门,而是执行以下操作

    if(!result.DepartmentReference.IsLoaded)
    {
    result.DepartmentReference.Load()
    }
    

    How to: Explicitly Load Related Objects

    【讨论】:

    • OSU 不存在 isLoaded 属性 :(
    • @user1391118,您使用的是 EF 4.0 吗?
    • 我用的是Visual Studio 2010自带的
    【解决方案2】:

    我认为 Northwind 中的 Products 和 Categories 表与您的需要相似。我会写一个这样的查询:

            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 };
    

    【讨论】:

    • @user1391118 也许我错过了一些东西,但我的示例如下。 Products 表具有 CategoryID 到 Category 表的外键。您无需执行任何连接即可访问“父”表(存在类别名称),只需从 prod.Category 导航属性访问它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多