使用一个大的 EF4 模型,我正在尝试做一些相同的事情,这可以在 linq2sql 中使用单独的 dbml 完成。我遇到的一个基本问题,很可能代表我对 linq 到实体的基本知识缺乏,你如何使用结果引用在被引用的表中查找对象?
例如,我有 4 个表,它们都通过外键链接在一起。
从概念上讲,我可以在结果引用上使用 foreach 遍历所有表,但是看起来很笨拙,如何使用 linq 来编写下面的代码?
//Get book
var book= db.books.SingleOrDefault(d => d.bookId == 286);
//If no book, return
if (book == null) return null;
//Get the shelf associated with this book
List<shelf> slist = new List<shelf>();
foreach (reading r in book.readings)
{
foreach (event re in r.events)
{
slist.Add(re);
}
}
List<event> bookevents = slist.Distinct().ToList();
//Get the customers associated with the events
List<int> clist = new List<int>();
foreach (event eb in bookevents)
{
var cust = db.customers.Where(c => c.customerID == eb.inID || c.customerID == eb.outID).ToList();
clist.AddRange(cust.Select(c => c.customerID));
}
//Return the list of customers
return clist;
编辑:我把它简化为 3 个步骤,发布这个以防其他人遇到类似问题。我欢迎任何关于如何更优雅地做到这一点的评论
//Get book
var book= db.books.SingleOrDefault(d => d.bookId == 286);
//If no book, return
if (book == null) return null;
//Get the bookevents associated with this book
var bookevents = (from reading in book.readings
select reading.events).SelectMany(e => e).Distinct();
//Get the customers associated with the events
var clist = (from be in bookevents
from c in db.customers
where c.customerID == be.inID || c.customerID == be.outID
select c.customerID).ToList();
//Return the list of customers
return clist;