c# - 使用导航属性获取数据

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

我正在使用 Entity Framework 创建应用程序。我已经从 Database.here 加载了数据库模型。在 Course 表中,DepartmentNavigation Property,DepartmentID 是外键。我创建了一个 gridview 并将其数据源设置为 Course Table,但我想查看 Department 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.

请告诉我如何解决?

最佳答案

我认为 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 };

关于c# - 使用导航属性获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10620500/

相关文章:

c# - 消息框中的文本应该是下一行

c# - 如何在自定义 SSIS 组件中创建目标列?

c# - 在 C# 中的 Linq 语句中使用 Take 时如何返回全部

sql - 按新指南排序以获得随机顺序

c# - 我在哪里可以找到同时遵守 OOP 原则和 SOLID 原则的代码示例?

c# - C# 谓词生成器混淆

javascript - 从 InnerHtml 添加链接按钮

c# - 尽管 intellisense 列出了定义,但找不到定义?

asp.net - 您可以在 MVC 中添加密码验证的地方?

c# - Asp.Net 弹出错误信息