.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

EF4/Linq Eager Loading with Include fails to populate all results

Posted By:      Posted Date: August 30, 2010    Points: 0   Category :ASP.Net
Hi, I'm trying out EF4 as part of a .Net 4.0 WCF service. The aim of the service is to return document data as an array of entity objects to any of our ASP.Net apps. The apps are still in .Net 2.0. Due to the nature of the solution I've disabled LazyLoading at context level. I started with this:var revQuery = from revs in context.DocRevision                         where (revs.ID == myIDVar)                         select revs;  Everything works ok, I receive the correct number of populated objects. However when I add an Include into my query to allow us to pickup fields from a related table that has a defined navigation only the first record is returned fully populated to a calling application:var revQuery = from revs in context.DocRevision.Include("StaffNames")                         where (revs.ID == myIDVar)                         select revs;  The array is the correct size but all elements after the first are blank, default placeholders. Its like using the Include has reverted to LazyLoading and I can't seem to kick it into line. Anyone else had this problem?

View Complete Post

More Related Resource Links

Need Syntax To Make Results of LINQ Union Return Non-Generic Type



I have the below SQL which works just fine:

SELECT     Message, CreateDate, AccountId, AlertTypeId
FROM       dbo.Alerts
SELECT     TOP (100) PERCENT Status, CreateDate, AccountId,
                          (SELECT     10 AS Expr1) AS AlertTypeId
FROM         dbo.StatusUpdates
WHERE AccountId = PassedInParameter

I have been going about trying to convert the above into a LINQ method and am having problems with return types.
As the above SQL illustrates, I am querying two distinct LINQ tables - Alerts and StatusUpdates -
and then attempting to perform a Union on them. In order to do the union in LINQ, I have to have agreeing types. So, I
am using "var" to make the results of "alerts" and "updates" generic before the union.  

public IList GetStatusUpdatesAsAlertsByAccountId<T>(Int32 accountId)
            using (WorkbookDataContext dc = _conn.GetCont

Linq query results to List collection



I have a GridView in my page. I want to use below code in code beind. query nothwing DB using linq . add linq query result to new list and then bind list as gridview Datasource

I use below code . But I don't know how to add results to List? Could any one tell me how !

Public Class OrderCity
        Private _name As String
        Private _city As String
        Public Property name As String
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value

            End Set
        End Property
        Public Property city As String
                Return _city
            End Get
            Set(ByVal value As String)
                _city = value

            End Set
        End Property
    End Class
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim dbe As New SFFAV1DataContext
        Dim latestadsDs = From p In dbe.Products _
                            Select New With {p.Title, p.ProducedCity} _
                             Take (2)

        Dim FilteredList As New List(Of OrderCity)()
        For Each result In latestadsDs
            Dim Menedfcou = Nothing
            FilteredList.Insert(0, Menedfcou)

Linq and stored procedure - cannot get results


Hi to all,

i try call a stored procedure from my linq code in order to validate a user credentials. I have tried via linq to sql and sql commands and everything works as expected. But when comes to calling a stored procedure via linq, i cannot get the results i expect.

This is my code:

stored procedure:

ALTER PROCEDURE [dbo].[ValidateUser] (@UserName varchar(50), @UserCode varchar(4))

	SELECT ISNULL(FirstName, ''), ISNULL(LastName, '')
	FROM Users
	WHERE (UserName =@UserName AND UserCode=@UserCode)


                dbContext = new MyDBDataContext();
                var result = dbContext.ValidateUser("Jim", "1234");

                if(result != null)
                    //true, so user is validated so set response status to OK
                    response.Status = ResponseStatus.OK;

                    //set returned params to response
                    var paramsReturned = result.FirstOrDefault();

                    response.FirstName = paramsReturned.Column1;
                    response.LastName = paramsReturned.Column2;
                    //false, so set respone to the corresponding error

Help with linking LINQ results to a grid



I'm getting the following error message when running the code below: yx returns a value of '1' for example

Error: Both DataSource and DataSourceID are defined on 'GridView4'. Remove one definition


Dim vc1 As Integer

For Each row As GridViewRow In GridView2.Rows

'Find checkbox in the row

Dim chb As CheckBox = DirectCast(row.FindControl("CheckBox1"), CheckBox)

'if checkbox is found and is checked then add the id to string

If chb IsNot Nothing AndAlso chb.Checked Then

If vc1 > 0 Then

yx = yx & "'" & row.Cells(1).Text & "'"


yx = "'" & row.Cells(1).Text & "'"

End If

vc1 = vc1 + 1

End If


' MsgBox(yx)

Dim DB As New AOP29ClassesDataContext

Dim Query = From p In DB.Link_Tables _

Where p.Link_ID Like yx _

Select New With {p.Receiver.Receiver, p.Donor.Donor}


GridView4.DataSource = Query


Any ideas how to fix this problem? Using the design property of the grid, I tried removing the datasource link from the grid but the grid doesn't appear unless the data source in linked to a table.


Loading IFilter from Sharepoint Timerjob context fails silently


We are having trouble using the IFilter ILoadFilter Interface within the context of a SharePoint Timer Job.

The code we have written works fine when executed within the SharePoint w3wp context. But when the same code is executed within the context of a SharePoint Timer Job the ILoadFilter function just returns NULL.

Does anyone has suggestions for loading IFilters within SharePoint?

Kind regards,
Joran Markx

Joran Markx DiVa BV (The Netherlands) Blog - http://blog.diva.nl Website - http://www.diva.nl

Resource Loading Problem (2 UserControls, 1 Load works, 1 Fails. Both UserControls and the Resource


I am having an issue where I have 2 WPF UserControls loading a PNG file from codebehind, the png loads fine in one UserControl, but fails in the other.


This is the top of the codebehind for the UserControl that works...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.ComponentModel;

using ModuleInterface;
using System.Reflection;
using System.Windows.Threading;

Help: populate Html.DropDownList from table data? [Linq to SQL model]


I have two tables, Users and Roles.  The roles table is a reference table for the different roles of my site (RoleId and RoleName columns). The Users table contains profile data for each user, including a RoleId column that is FK'd back to the Roles table [RoleId].

Both tables are in a Linq to SQL model.

I have an edit page created which lists all the profile values of a user.  The edit page inherits the User model.  One of the editable values is the RoleId field.  I want to set this up to be a drop-down list that contains items labeled using the RoleName column of the Roles table, and matched with values of RoleId.

How can I achieve this?

Getting a Single node, in linq results to:


A part of my rawXML i get from a webservice:

<GetOpties>\n  <Table>\n    <nOptieLijstIDHist>167613</nOptieLijstIDHist>\n    <Code>W01</Code>\n    <Omschrijving>ADVANCE PAKKET</Omschrijving>\n    <Prijs>1990</Prijs>\n    <Bijzonderheden>Lichtmetalen velgen Porto 7J x 17\" met 22545 R17 banden + 15 mm verlaagd onderstel + straffe demping en versterkte vering + 35% getint glas achter</Bijzonderheden>........ 

I try to get the the values in a linq query:

var query = from feed in xml.DocumentElement.ChildNodes.Cast<XmlNode>()
                            select new AutoDiskClass.Options
                                nOptieLijstIDHistField = feed.SelectSingleNode("nOptieLijstIDHist").InnerText,

How to populate ListView via LINQ to SQL?


Here's my C# cobe behind:

protected void btnSearchWrd_Click(object sender, EventArgs e)
        insLusHmoobDataContext editLus = new insLusHmoobDataContext();
        var lus = from wrd in editLus.lusHmoobs where wrd.word.Trim().ToLower().StartsWith(txtWord.Text.Trim().ToLower()) select wrd;

        ltvLusHmoob.DataSource= lus;

<asp:ListView ID="ltvLusHmoob" runat="server" DataKeyNames="wordID" 
            GroupItemCount="3" onitemcommand="ltvLusHmoob_ItemCommand">
                <td runat="server" style="background-color:#FFF8DC;">
                    <asp:DynamicControl runat="server" DataField="word" Mode="ReadOnly" />
                    <br />
                <td runat="server" style="background-color:#008A8C;color: #FFFFFF;">
                    <asp:DynamicControl runat="server" DataField="word" Mode="Edit" />
                    <br />
                    <asp:Button ID="UpdateBut

Linq to Sql multiple results



I am kartheek. I had some doubt regarding Linq to Sql multiple results. I am new to Linq.

The following is my code, please help me.

My sql procedure is 

ALTER procedure [dbo].[GetParentResourcesDataWithFilters]
@ResourceClubId bigint,
@Keyword varchar(100),
@Status varchar(10),
@CurrentPage int,
@RecordsPerPage int
as begin

Pass Linq results to another function


I have 2 linq queries, 1 get data by name the other by id, both return the same data and I want to populate the same form with it, but I can't seem to pass the results to a method and still have intellisense.

Basically something like this:

protected void uxSearchUserName_Click(object sender, EventArgs e) {
     if (SearchingByName){
          var selUserData = Entites.UserTable.FirstOrDefault(un => un.Name == uxUserName.Text);
          var selUserData = Entites.UserTable.FirstOrDefault(un => un.id == uxUserID.Text);     }

public void BuildForm(results){
     string Name = results.Name;
     ......populate fields with data from results

I found examples where I have to create a property for each field but that will get tedious with large datasets. Was hoping there's an easier way.



How to include element 'imageurl' in custom search results

Hi All,
Well, this one is a bit of a puzzler... I've written a custom Advanced Search by adding my own properties exampled:

KeywordQuery kQuery = new KeywordQuery(ServerContext.Current);
resultTbls = kQuery.Execute();
tblResult = resultTbls[ResultType.RelevantResults];

The issue is I cannot reference element 'imageurl' in the XSL because of my custom properties. If I don't add any custom properties then 'imageurl' returns as default as expected. I also cannot do the following as it raises an exception:

Is there a way to include element 'imageurl' whilst having custom properties? Or is the default search results working its magic and applying 'pixie dust' in generating element 'imageurl?'

The section xsl looks like this:
<xsl:template match="Result">
  <xsl:variable name="id" select="id"/>
  <xsl:variable name="url" select="url"/>
  <span class="srch-Icon">
   <a href="{$url}" id="{concat('CSR_IMG_',$id)}" title="{$url}">
   <img align="absmiddle" src="{imageurl}" border="0" alt="{imageurl/@imageur

Playing with Linq grouping: GroupByMany?

One of its features is grouping. Many people understand grouping like it is defined in Sql. Linq is implementing grouping quite the same way. Let's discover this syntax and how to make consecutive groups easier.

LINQ : Implementing IN and NOT IN

I got tried of typing

var result = from s in source
where items.Contains(s)
select s;and so I implemented the IN and NOT IN methods as extension methods:

101 LINQ Samples Tutorials

101 LINQ Example with sample code snippets....This sample prints each element of an input integer array whose value is less than 5. The sample uses a query expression to create a new sequence of integers and then iterates over each element in the sequence, printing its value

Linq: how to share parameters between lambda expressions ?

When using Linq to objects, you will quickly feel the need to pass some parameters from a method to another but it's not so easy because each Linq method is not calling the following one. In a Linq sequence, each method is using the result computed by the previous one. So, local contexts are not visible from one method to another.
The compiler is using two technical different ways to let parameters go out of a method.

Linq to Sql CompiledQuery container

Ok now let's go. Here is just a little trick but with some interesting patterns that could be useful in some other contexts not connected to Linq to Sql.

When using Linq expressions, like with Linq to Sql, translating the expression into something else (sql for example) is taking time and resources. Sometimes it's negligible, sometimes not...
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend