force a Linq-To-Entities query to get all related objects when getting a parent object

All --

Please help.

How can one force a Linq-To-Entities query to get all related objects when getting a parent object? Is there a way to set the depth of the query?

Please advise.

For an example, check below for the code... 

 

public Team.DynamicData01.Business.Entities.TestCoreRecord GetEntity(long targetId)
{
 Team.DynamicData01.Business.Entities.TestCoreRecord myEntity = null;

 using (Team.DynamicData01.Business.Entities.NorthwindEntityManager myContext = new Team.DynamicData01.Business.Entities.NorthwindEntityManager())
 {
  var q = from p in myContext.TestCoreRecord
    where (p.ID == targetId)
    select p;

  if ((q == null) || (q.Count() <= 0) || (q.First() == null))
  {
   myEntity = null;
  }
  else if (q.Count() == 1)
  {
   Debug.WriteLine("q.Count().ToString()='" + q.Count().ToString() + "'");
   myEntity = (Team.DynamicData01.Business.Entities.TestCoreRecord)(q.First());

   // - CULPRIT - This always returns 0 when it should return 1, so how can one get the related objects to fill at query time.
   Debug.WriteLine("myEntity.TestColorCode.Count().ToString()='" + myEntity.TestColorCode.Count().ToString() + "'");
  }
  else
  {
   Debug.WriteLine("q.Count().ToString()='" + q.Count().ToString() + "'");
   throw new System.ApplicationException("A fetch where targetId='" + targetId.ToString() + "' returned q.Count()='" + q.Count().ToString() + "'.");
  }
 }

 return myEntity;
}

 

 


USE [Northwind]
GO
/****** Object:  Table [dbo].[TestColorCode]    Script Date: 01/22/2009 14:12:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TestColorCode](
 [ID] [bigint] IDENTITY(1,1) NOT NULL,
 [Name] [nvarchar](64) NOT NULL,
 [Description] [nvarchar](128) NOT NULL,
 CONSTRAINT [PK_TestColorCode] PRIMARY KEY CLUSTERED
(
 [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [IX_TestColorCode] UNIQUE NONCLUSTERED
(
 [Name] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

 

 

USE [Northwind]
GO
/****** Object:  Table [dbo].[TestCoreRecord]    Script Date: 01/22/2009 14:12:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TestCoreRecord](
 [ID] [bigint] IDENTITY(1,1) NOT NULL,
 [FName] [nvarchar](32) NOT NULL,
 [LName] [nvarchar](32) NOT NULL,
 CONSTRAINT [PK_TestCoreRecord] PRIMARY KEY CLUSTERED
(
 [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

 


USE [Northwind]
GO
/****** Object:  Table [dbo].[TestCoreRecordTestColorCodeLink]    Script Date: 01/22/2009 14:13:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TestCoreRecordTestColorCodeLink](
 [TestColorCodeID] [bigint] NOT NULL,
 [TestCoreRecordID] [bigint] NOT NULL,
 CONSTRAINT [PK_TestCoreRecordTestColorCodeLink] PRIMARY KEY CLUSTERED
(
 [TestColorCodeID] ASC,
 [TestCoreRecordID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[TestCoreRecordTestColorCodeLink]  WITH CHECK ADD  CONSTRAINT [FK_TestCoreRecordTestColorCodeLink_TestColorCode] FOREIGN KEY([TestColorCodeID])
REFERENCES [dbo].[TestColorCode] ([ID])
GO
ALTER TABLE [dbo].[TestCoreRecordTestColorCodeLink] CHECK CONSTRAINT [FK_TestCoreRecordTestColorCodeLink_TestColorCode]
GO
ALTER TABLE [dbo].[TestCoreRecordTestColorCodeLink]  WITH CHECK ADD  CONSTRAINT [FK_TestCoreRecordTestColorCodeLink_TestCoreRecord] FOREIGN KEY([TestCoreRecordID])
REFERENCES [dbo].[TestCoreRecord] ([ID])
GO
ALTER TABLE [dbo].[TestCoreRecordTestColorCodeLink] CHECK CONSTRAINT [FK_TestCoreRecordTestColorCodeLink_TestCoreRecord] 

 

Thank you.

-- Mark Kamoski


http://www.NetBrainer.com
0
mkamoski
1/22/2009 7:19:06 PM
asp.net.sql-datasource 29906 articles. 0 followers. Follow

1 Replies
1117 Views

Similar Articles

[PageSpeed] 14
Get it on Google Play
Get it on Apple App Store

All --

This is an update to my post above.

I found a way that works but is stinks because it requires hard-coding an entity name in the Linq-To-Entities query.

(See the code below for details.)

Is there a way to avoid hard-coding here?

Please advise.

 

Here is the sample code...


public Team.DynamicData01.Business.Entities.TestCoreRecord GetEntity(long targetId)
{
 Team.DynamicData01.Business.Entities.TestCoreRecord myEntity = null;

 using (Team.DynamicData01.Business.Entities.NorthwindEntityManager myContext = new Team.DynamicData01.Business.Entities.NorthwindEntityManager())
 {

  var q = from p in myContext.TestCoreRecord.Include("TestColorCode")
    where (p.ID == targetId)
    select p;

  if ((q == null) || (q.Count() <= 0) || (q.First() == null))
  {
   myEntity = null;
  }
  else if (q.Count() == 1)
  {
   Debug.WriteLine("q.Count().ToString()='" + q.Count().ToString() + "'");
   myEntity = (Team.DynamicData01.Business.Entities.TestCoreRecord)(q.First());

   // - CULPRIT - This always returns 0 when it should return 1, so how can one get the related objects to fill at query time.
   Debug.WriteLine("myEntity.TestColorCode.Count().ToString()='" + myEntity.TestColorCode.Count().ToString() + "'");
  }
  else
  {
   Debug.WriteLine("q.Count().ToString()='" + q.Count().ToString() + "'");
   throw new System.ApplicationException("A fetch where targetId='" + targetId.ToString() + "' returned q.Count()='" + q.Count().ToString() + "'.");
  }
 }

 return myEntity;
}
 

Thank you.

-- Mark Kamoski


http://www.NetBrainer.com
0
mkamoski
1/22/2009 7:24:08 PM
Reply:

Similar Artilces:

Getting an "Object reference not set to an instance of an object", and no idea which object
I'm working on one of our ASP.NET 2005 projects now.  For the longest time we've gotten an error when compiling it that says, "Object reference not set to an instance of an object".  However, the irritating thing is it doesn't say what "object" its having problems with, and it certainly isn't telling me which file that has the problem.  So, I'm getting this error message that doesn't tell me where the error comes from.  All I know is that the error is "Out there".  Reminds me of an old X-Files episode. How am I t...

PB9.0.1 b7119
All: I have migrated PB8.0.3 PBLs in PB9.0.1 b7119. After migration, successfully connected to the PVCS7.5.1.0 b297. While visiting pbls (in PB), some of the pbls has green dot, green dot with ? mark and circle with + sign for objects. Some of the pbls has only + sign for all the objects (I am aware about the meaning of the symbol). Q: I am not sure why many of the objects having + sign since the objects are already resides in PVCS SC. Q: Since some of the objects has circle with + sign that means those objects gone out of sync with PVCS. Does it mean during migration the code h...

Getting the name of the object (the name of the object in the library)
Is there a way to get the name of an object as named in the library? I have a user object named ucb_user_object.. I put it in a window and I named it cb_1 The ClassName() function will return cb_1 but I want the function to return "ucb_user_object". Any of you have an idea ? Have a look at ClassDefinition, and following the ParentClass attribute up the chain. Extend this enough, and you can identify all descendants of ucb_user_object (I'm guessing that may be your objective). PFC implements something like this in (pfcapsrv.pbl)pfc_n_cst_metacl...

Accessing a Com object using Get Object
* Wasn't sure which section to put this in, but found similiar topics in here. We have a slight problem trying to access a COM Object. Reading some of the threads in this forum, people have mentioned trying to connect to a COM Object, but everyone has suggested using CreateObj. We cannot do this as the object is already created, we need to Get this object. Obviously you can use the GetObj command in VB6, but we cannot find away of Getting this object either through a webservice. Feel free to move this to the correct forum. Any help will be greatly recieved. Regards C ...

How to get DataTable object from DB and get Values from it
Here the code I use ...  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);        SqlDataAdapter Adptr = new SqlDataAdapter("Select * from AccountType ", con );DataTable mytbl = new DataTable("tbl"); Adptr.Fill(mytbl)       if (mytbl.Rows[0][1].ToString()) == "Classic")  /// Here I gey a message : There is no row 0 in table .... I checked DataTable with Response.Write( mytbl.Rows.Count )  it gives me 0 ... What can be the pro...

How to get cast a Repository Object to a PDM Object?
Hi, I have to code some tools that must read the repository directly. I can read all repository folders and repository objects, but the repository object doesn't show every object properties that i need. Example: I have the repository objects that represents PDM Columns of a Table. I can see the column code, but i can't see the column data type. I tried to cast the repository objetct to a PDM object, but didn't work. A piece of the code (in C#) is bellow. How can it be done? Thanks, Marcelo Tropia .... .... PdPDM.Column coluna = null; foreach (PdRMG.RepositoryObje...

Get Objects Parent Control
I have a control. I want to keep trying to get its parent until the parent is a datarow. How can I do this? e.g. Dim s as object = ..... Dim dr as Datarow While s.GetType.Equals(dr) ''Note that the following line is not available. s = s.GetParent End WhileIntelligence is a burden.Jagdip Singh AjimalManchester (and yes, I am a Manchester United fan)  USE Control.Parent Property in Recursive function. Base Condition should be in Parent is NULL Or Parent is Datarow. Somnath Mali.NET Developer , Pune INDIA.Please Mark As Answer If my reply helped you. You will need ...

How to get query from odbccommand object
Hello, I have created a sample page for user information, which request data from user and save in sql server 2005 database, so I have used ODBCConnection and ODBCCommand, ODBCCommand object read data using paramates, but I need the excat query whcih is running. When I tried to get command.CommanText its shows without paramaters..."INSERT INTO Users (PKID, Username, Password, Email, PasswordQuestion, PasswordAnswer, IsApproved) Values(?, ?, ?, ?, ?, ?, ?) so what should I do ...                OdbcConnection conn...

POST GET GET GET GET... WTH?
Hi, I'm at a loss to explain this... I have an ASPX page that I can't always navigate to. When I developed the app (it's Starter Kit Portal-based), I did it on my LAN and have had no trouble accessing the page. However, upon deployment, I see the following behavior: 1. POST request goes out looking for MyForm.aspx 2. GET request for MyForm.aspx 3. GET request for MyForm.aspx 4. ... X. GET request Sometimes, the page finally loads. Other times, it just ends up blank. Many times, it doesn't load at ALL the first POST - I just get a "The pa...

Why am I getting Object reference not set to an instance of an object in this code ?
   Hi ;    I am trying to nest two gridview controls using two Access views.    And I am using the Microsoft walkthrough Creating a nested gridview control as an example.    But when I get to this step creating the row data bound event for the parent gridview I get the Object Ref not set message.    Why ?1 Imports System.Data.OleDb 2 3 4 5 Partial Class Default7 6 Inherits System.Web.UI.Page 7 8 Protected Sub Gridview1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.Gr...

SQL DataSource : Object Reference not set to an instance of an object
 Dear friendsI am getting this error from few days (it was not in past)when i add new "sqlDataSource" , I set the Server name, user name and password then i select the Database, when i click on "Test Connection" button, it does not give me any Error and it shows that Test connection Successful, but when i click "OK", It shows the Error box with the error "Object Reference not set to an instance of an object"From few days it is happening, I was seting the datasource without any problem in past.I am using SQL Server 2005Any one can help? aliusmankha...

getting Object reference not set to an instance of an object for ContentPlaceHolder
hi -  I have created one master lovem.master and content lovec.aspx pages.  In master I have the search textbox, radio buttons and Search button.  In content page I have a gridview which should be populated when criteria is entered and 'look book' button is clicked on master page.  The method to connect to database and populate content page's gridview is located in master page.  When entered any character in textbox and selected either of title or author radio buttons and clicked 'Look book' ,  i'm getting the follwoing error. Exception D...

How to get name: Object reference not set to an instance of an object.
How do I programmatically get the name of the object that in not instantiated when I get this error: "Object reference not set to an instance of an object." (If I can get the name, I can add it to my error logs so we can diagnose problems quicker)1 Dim oReporterCandidate As clsReporterCandidateBL 2 oReporterCandidate.Add(iCreatedByUserID, DateTime.Now(), iManagerUserID, iCandidateUserID) 3 Note: Add() is not static/shared  So when this code above crashes, I want the catch statement to be able to work out the name of the object ...

Getting the name of one object below another object in a dw
Hi All. PB9.0 I am writing a move column service for my tabular dws to allow users to drag and drop columns to change their order (This should be native to PB!). The problem I am having is how to determin the name of an object which is below the object returned using either getobjectatpointer or the object returned by the mouse move event. Backgound info. When the user holds down a certain key and left clicks the mouse on the column header, I dynamically create a copy of the object and move it with the mouse as the user moves the mouse. I want to then put a highlighter object be...

Web resources about - force a Linq-To-Entities query to get all related objects when getting a parent object - asp.net.sql-datasource

Resources last updated: 12/7/2015 7:14:45 AM