1

使用一个大的 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;
4

1 回答 1

2

尝试这个:

var distinctEvents = (from event in db.events
               join reading in db.readings on event.readingID equals reading.readingID
               where reading.bookID == 286
               select event).Distinct();
               // if you want to see this bookID is present in Book table, you should add a join statement like "join book in db.books on reading.bookID == book.bookID"
var custIdList = from c in db.customers
                 from event in distinctsEvents
                 where c.customerID == event.inID || c.customerID == be.outID
                 select c.customerID;

return custIdList.ToList();
于 2012-08-04T18:25:18.233 回答