EF4模型通过使用linq到实体的结果外键进行引用



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

试试这个:

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();

最新更新