您必须知道您的 dbContext 代表您的数据库。 DbSet 代表数据库中的表
在实体框架中,表的列由类的非虚拟属性表示。虚拟属性表示表之间的关系(一对多,多对多,...)
您的数据库将包含Recipes 和Ingredient。每个Recipe 都会有零个或多个Ingredients,而每个Ingredient 会使用零个或多个Recipes:简单的多对多关系。
您将拥有表 Recipes 和 Ingredients,因此您的 dbContext 将为它们提供 DbSets:
class MyDbContext : DbContext
{
public DbSet<Recipe> Recipes {get; set;}
public DbSet<Ingredient> Ingredients {get; set;}
}
class Recipe
{
public int Id {get; set;} // primary key
... // other columns
// every Recipe has zero or more ingredients (many-to-many)
public virtual ICollection<Ingredient> Ingredients {get; set;}
}
class Ingredient
{
public int Id {get; set;} // primary key
... // other columns
// every Ingredient is used in zero or more Recipes( many-to-many)
public virtual ICollection<Recipe> Recipes {get; set;}
}
因为我在两边都使用了virtual,Recipes 和 Ingredients,实体框架可以检测到我设计了一个多对多。实体框架甚至会为我创建一个联结表,我不必声明它。
// Fetch all Desserts with their Bitter ingredients
var desertsWithoutSugar = myDbContext.Recipes
.Where(recipe => recipy.Type == RecipyType.Dessert)
.Select(recipe => new
{
// select only the properties that I plan to use:
Id = recipe.Id,
Name = recipe.Name,
...
// not needed: you know the value: Type = recipe.Type
Ingredients = recipe.Ingredients
.Where(ingredient => ingredient.Taste == Taste.Bitter)
.Select(ingredient => new
{
// again: only the properties you plan to use
Id = ingredient.Id,
Name = ingredient.Name,
})
.ToList(),
})
实体框架知道您的多对多关系,并且足够聪明,可以检测到三个表(包括联结表)需要(组)联接。
如果你想设计一个一对多的关系,例如一个学校和他的学生,你只在一侧声明virtual ICollection。另一方得到外键。这是您表中的一列,因此是非虚拟的
class School
{
public int Id {get; set;}
...
// every School has zero or more Students (one-to-many)
public virtual ICollection<Student> Students {get; set;}
}
class Student
{
public int Id {get; set;}
...
// Every Student studies at one School, using foreign key
public int SchoolId {get; set;}
public virtual School School {get; set;}
}
public SchoolContext : DbContext
{
public DbSet<School> Schools {get; set;}
public DbSet<Student> Students {get; set;}
}
根据我的经验,由于我使用实体框架,我几乎不必再进行 (Group-)join,我使用集合:
给我所有学校和他们的学生
var Result = dbContext.Schools
.Where(school => ...)
.Select(school => new
{
Id = school.Id,
...
Students = school.Students
.Where(student => ...)
.Select(student => new
{
Id = student.Id,
...
})
.ToList(),
});
类似的:给我他们就读的学校的所有学生