因此,您有一个 name,并且您希望所有使用此名称引用 Student 的 Textings,以及使用此名称引用 Staff 成员的所有 Textings。
我的建议是将学生短信与员工短信联系起来。你可以在一个大的 LINQ 语句中做到这一点,但这会让人很难理解。所以我会分两步做,然后在一个查询中连接它:
const int student = 1;
string name = "William Shakespeare";
var studentTextings = textings.Where(texting => texting.PersonTypeId == student)
.Join(students.Where(student => student.Name == name),
texting => texting.PersonId, // from every Texting take the foreign key
student => student.Id, // from every Student take the primary key
// parameter resultSelector:
// from every texting with its matching student make one new:
(texting, studentWithThisTexting) => new
{
// Select the Texting properties that you plan to use
Id = texting.Id,
...
}
换句话说:在所有短信中,只保留那些涉及学生的短信,这样您就知道外键是指学生表中的主键。从所有学生中只保留具有请求名称的学生。
加入所有剩余的短信和少数剩余的在主键和匹配外键上有此名称的学生。
为员工做类似的事情:
const int staff = 2;
var staffTextings = textings.Where(texting => texting.PersonTypeId == staff)
.Join(staffMembers.Where(staffMember => staffMember.Name == name),
texting => texting.PersonId, // from every Texting take the foreign key
staffMember => staffMember.Id, // from every Staff member take the primary key
// parameter resultSelector:
(texting, staffMembers) => new
{
// Select the Texting properties that you plan to use
Id = texting.Id,
...
}
现在你要做的就是连接这两个。请注意:您只能 Concat 相似的项目,因此两个 Join 中的 resultSelector 应该选择完全相同类型的对象。
var textingsOfPersonsWithThisName = studentTextings.Concat(staffTextings);
还有改进的余地!
如果您仔细观察,您会发现短信表会被扫描两次。原因是你的数据库没有规范化。
有没有可能,给学生发短信会变成给员工发短信?如果没有,我的建议是制作两张表:StudentTextings 和 StaffTextings。除了查询会更快,因为您不必检查PersonType,这还有一个好处是,如果稍后您确定 StudentTexting 与 StaffTexting 不同,您可以更改表格而不会遇到问题。
如果您确实认为有时需要更改短信的类型,并且您不想通过创建新短信来做到这一点,那么您还应该有两个表格:一个带有 StudentTextings,一个带有 StaffTextings,这两个表都与短信具有一对一的关系。
所以学生与 StudentTextings 是一对多的,而 StudentTextings 与 Textings 是一对一的。 Staff 和 StaffTextings 类似。
所以学生 [4] 有 3 个学生短信,ID 为 [30]、[34]、[37]。这些 StudentTexting 中的每一个都有一个外键 StudentId,其值为 [4]。每个 StudentTexting 用外键引用自己的 Texting:[30] 指的是 texting [101],所以它有外键 101,等等。
现在,如果发短信 [101] 必须成为员工 [7] 的发短信,您必须删除引用 [101] 的 StudentTexting 并创建一个引用员工 [7] 和发短信 [101] 的新员工发短信]
顺便说一句,由于组合 [StudentId, TextingId] 将是唯一的,表 StudentTextings 可以使用这个组合作为主键。 StaffTextings 类似