连接2个表并在LINQ中返回结果。

huangapple go评论82阅读模式
英文:

Join 2 tables and return the resulting one in LINQ

问题

db.Patients.Join(db.Studies, ct => ct.Studyid, st => st.Studyid, (ct, st) => st)
  .Where(p => p.Patientstudyid == PatId)
  .ToList()
英文:

I have 2 tables Patients and Studies that have a shared field called Studyid. I need to get the study name from the Studies table
where PatID is a method's parameter.
I am joining the tables but I am failing to return the resulting one, so far I am retuning a single table to which I cannot implement the Where condition.

db.Patients.Join(db.Studies, ct => ct.Studyid, st => st.Studyid, (ct, st) => st).Where(p => p.Patientstudyid == PatId).ToList() which obviously won't work since Studies have no patient's information.

How to return the joined table?

答案1

得分: 2

我更喜欢在使用连接时使用查询语法。这样更容易重构和理解查询的作用。
英文:

I would prefer query syntax when using joins. It is easily to refactor and to understand what query do.

var query = 
    from p in db.Patients
    join st in db.Studies on p.Studyid equals ct.Studyid
    where p.Patientstudyid == PatId
    select st.Name;

var result = query.ToList();

huangapple
  • 本文由 发表于 2023年3月1日 15:50:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定