Join顾名思义就是用来连接两张表的操作,下面我们来定义另外一张表,叫AccountType表:
csharpcsharppublic class AccountType
{
public int AccountTypeId { set; get; }
public string TypeName { set; get; }
}
用来表示会员的类型,比如普通会员、VIP会员等。然后在Account表中,我们需要加上AccountTypeId字段,用来表示此账号属于哪个账号类型的。那么很明显,如果要连接这两张表,那就需要AccountTypeId这个。
下面我们来看一下,怎么使用Join来链接这两张表:
csharpcsharpvar a = context.Account.Join(
context.AccountTypes,//要链接的表
account => account.AccountTypeId,//主表的关联字段
accountType => accountType.AccountTypeId,//链接表的关联字段
(account, type) => new //拼接成一个新实体 匿名对象
{
Person = account,
PersonType = type
}
)
.Select(p => new //使用select选择需要的字段
{
p.Person.LastName,
p.Person.FirstName,
p.PersonType.TypeName
});
Group Join的使用,就是分组和表连接的结合使用。为了讲这个,我们需要重新建两张表,我们就以论坛为例,一个论坛有主题表和帖子表,主题表是保存楼主帖和标题的,帖子表是保存回复的帖子:
csharpcsharppublic class Theme
{
public int ID { set; get; }
public string Title { set; get; }
public string Content { set; get; }
}
Group by的使用、Distinct的使用(过滤重复记录)、Union的使用、Intersect的使用、Except的使用。
Previous: 11节-复杂类型和枚举
Next: 复杂查找