好吧,这个代码中会有相当多的代码,可能会有点长。也就是说,我真的很难找到最好的方法来做到这一点,任何帮助都会得到极大的赞赏。我在这里学习,特别是编写这些类型查询的最有效方法。
注意:我现在正在使用的系统是使用Entity Framework 6在VB.NET中编写的ASP.NET MVC站点。
尽管如此,我相信我最好的选择就是展示一个例子,看看有哪些选择。当我需要使用LINQ to Entities查询命中数据库来填充对象的属性时,我的问题就出现了,但其中一些属性本身既包含简单整数,也包含更复杂的对象。例如,请执行以下查询:
请注意,在下面的代码示例中,我删除了一个复杂的WHERE子句以及其他一些与我填充的问题属性无关的子句,使其更小,更易于阅读。
//NOTE: If any context is needed to better understand this, I can provide it. I do provide a bit in the comments. Actual code uses ' for comments (VB).
/*Context: db is an instance of the EF context. Code is representing threads
and replies in an "activity feed". Threads can have private recipients and
uploads, both of which are grabbed from the database. These are the two
properties I'm populating which this question addresses further down.*/
//Get all my activity feed threads
model.ActivityFeedThreads = (From thds In db.tblThreads
From thps In db.tblThreadParticipants.Where(Function(w) w.thpThread_thdID = thds.thdID).DefaultIfEmpty()
Join prns In db.tblPersons On thds.thdOwner_prnID Equals prns.prnID
Join emps In db.tblEmployees On prns.prnID Equals emps.empPerson_prnID
Where (thps Is Nothing And thds.thdPrivacy_lvlID = ActivityThread.ActivityThreadPrivacy.PublicThread) _
Select New ActivityThread With {.thdID = thds.thdID,
.Content = thds.thdContent,
.ThreadOwner_prnID = thds.thdOwner_prnID,
.PrivacyOption_lvlID = thds.thdPrivacy_lvlID,
.ThreadDate = thds.thdDateCreated}).Distinct().Take(20).OrderByDescending(Function(o) o.ThreadDate).ToList()
现在,我需要填充的一个未包含在该查询中的属性是" AttachedFiles",这是一个类型列表" AppFile",我们系统中的自定义类。此外,还有一个名为" PrivateRecipients"的第二个属性,它是一个简单的Int32列表。我试图将这些内容用于上述查询但没有成功,因此我必须遍历结果列表并填充它们,从而导致对数据库的大量命中。以下是我目前的代码:
//I need to get the private recipients for this post.. Is there a way to work this in to the above query? What's the most efficient solution here?
For Each threadToEdit In model.ActivityFeedThreads
threadToEdit.PrivateRecipients = db.tblThreadParticipants.Where(Function(w) w.thpThread_thdID = threadToEdit.thdID).Select(Function(s) s.thpPerson_prnID).ToList()
Next
//Again, loop through, grab all attached files. Similar situation as above.. Can I work it in to the query?
For Each threadToEdit In model.ActivityFeedThreads
threadToEdit.AttachedFiles = (From flks In db.tblFileLinks
Join fils In db.tblFiles On flks.flkFile_filID Equals fils.filID
Where flks.flkTarget_ID = threadToEdit.thdID And flks.flkLinkType_lvlID = AppFile.FileLinkType.Thread_Upload
Select New AppFile With {.filID = fils.filID,
.Location = fils.filLocation,
.FileURL = fils.filLocation,
.Name = fils.filName,
.FileName = fils.filName,
.MIMEType = fils.filMIMEType}).ToList()
Next
正如您所看到的,在这两种情况下,我不得不循环并多次访问数据库,而且我必须想象随着数据的增长,这将成为一个瓶颈..是LINQ to Entities有更好的方法吗?我应该改变我的方法吗?
提前感谢您的时间/帮助,非常感谢!