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

时间:2012-08-04 16:17:12

标签: c# entity-framework-4 linq-to-entities

使用一个大的EF4模型我正在尝试做一些相同的事情,可以使用单独的dbml在linq2sql中完成。我遇到的一个基本问题是,我可能是如何使用结果引用来查找被引用的表中的对象?

例如,我有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;

1 个答案:

答案 0 :(得分: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();