我正在使用Entity Framework创建App。我从Database.here加载了数据库模型在Course
表Department
中是Navigation Property
,DepartmentID
是外来的key.I创建了一个gridview并将其Datasource设置为Course Table,但是我希望看到Deaptment Name
而不是department ID
。我可以使用导航属性,如Department.count
但是我怎么能使用navigation属性从Department Table获取数据(部门名称)。
任何人都可以帮助我
这是我的代码
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.
请告诉我如何解决它?
答案 0 :(得分:0)
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()
}
答案 1 :(得分:0)
我认为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 };