Home » SQL Server

Reference child field from parent in update

I am new to L2S and I want to update some fields in a table.

I have a parent DispositionHold table which has a PK of DispositionHoldID and a child table, Disposition with a PK DispositionID and FK DispositionHoldID.

I want to reference the child PK DispositionID in a where clause and I want to update the parent DispositionHold table.

One query I tried:


var updateHold =
        (from dispositionHold in db.DispositionHolds
         where dispositionHold.Dispositions.DispositionID == dispositionID
         select dispositionHold).SingleOrDefault();

 I can't do this because I can't get to dispositionHold.Dispositions.DispositionID. I can only get to dispositionHold.Dispositions and then I get a list of extension methods. How can I reference the PK of the child table?





1 Answer Found


Answer 1

Ok so I tried this query which looks like it will work. I just reversed the query to come from the child table to the parent instead of the other way around.


var updateHold =
        (from disposition in db.Dispositions
         where disposition.DispositionID == dispositionID
         select disposition.DispositionHold).SingleOrDefault();



I have been having a problem trying to insert data in parent and child tables from CheckedListBox items.The parent table has the parentID and Name while in the child table, i have ParentID,ChildID,ChildDetail.I want to iterate and insert all child records. how do i go about it?

If you have a parent-child relationship between objects, which should hold the reference to the other?  For example, if my program had a Stores class and an Employee class, where employees are children of stores, to maintain the relationship would Employee have a .Store property, or would the Store keep a .Employees list?  Or both?

Maybe the question is too broad and depends on the specifics, but I was just wondering if there was a standard method.  Obviously if you are looking at the employee and need to know his store, it's easiest (and fastest) if the object has a built-in reference to its parent.  And vice-versa if looking at a store.  The most convenient would if both have references to each other, but then that means the need to update and maintain both pointers for changes like when an employee moves to another store.  So I think only one reference is best.



Got a simple table.  You've seen it before a million times.  Table has an ID (identity in this case) and a field called ParentId.  This is a nullable field which indicates the parent of this record.  Real complicated schema, I know.

Now, EF4 bails on me with the following validation error:

Error 2016: Condition cannot be specified for Column member 'ParentId' because it is marked with a 'Computed' or 'Identity' StoreGeneratedPattern.

I have no idea how to get around this.  What do?


I am having trouble communicating from a child form to a parent form. I am able to do it in C# but I am having trouble in C++. Essentially I have a main form that opens a different form for the use to assign values for variables in the main form. I have tried to follow some examples I have seen on the web but I keep getting errors.


Here is the code I am currently trying to use:


Main form:

#pragma once
#include <string>
#include "frmRadial.h"
#include "frmFreq.h"namespace TravelingMagnetics2 {

	usingnamespace System;
	usingnamespace System::ComponentModel;
	usingnamespace System::Collections;
	usingnamespace System::Windows::Forms;
	usingnamespace System::Data;
	usingnamespace System::Drawing;
	usingnamespace std;

	ref class frmRadial;
	/// <summary>/// Summary for Form1/// </summary>publicref class Form1 : public System::Windows::Forms::Form
		//The number of times a second the DA is polled for magnetometer updatesint Frequency;
		//Number of test points to be measuredint Radials;

			////TODO: Add the constructor code here//
			Frequency = 10;
			Radials = 12;

private: System::Void radialsToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
			 frmRadial^ f1 = gcnew frmRadial();

			 //frmFreq^ f1 = gcnew frmFreq();//f1->Show();


Child form:

#pragma once
#include "Form1.h"namespace TravelingMagnetics2 {

	usingnamespace System;
	usingnamespace System::ComponentModel;
	usingnamespace System::Collections;
	usingnamespace System::Windows::Forms;
	usingnamespace System::Data;
	usingnamespace System::Drawing;

	ref class Form1;
	/// <summary>/// Summary for frmRadial/// </summary>publicref class frmRadial : public System::Windows::Forms::Form
			////TODO: Add the constructor code here//

		void setParent(Form1^ f){
			pForm = f;
		/// <summary>/// Clean up any resources being used./// </summary>
			if (components)
				delete components;

		Form1^ pForm;
		/// <summary>/// Required designer variable./// </summary>
		System::ComponentModel::Container ^components;


I get the following errors:

1 error C2512: 'TravelingMagnetics2::frmRadial' : no appropriate default constructor available

2 error C2027: use of undefined type 'TravelingMagnetics2::frmRadial

3 error C2227: left of '->Show' must point to class/struct/union/generic type


I can't seem to find anything on these forums when I search. The code that I am using is what I found when I did a google search. I am hoping there is something stupidly simple that I am missing.


Thanks in advance



Yet another dilemma.  Using Access 2007 I have a datasheet subform bound to a table that has a child table with a

one-to-many relationship.  As I enter the child records in a datasheet view subform, how can I rollup the sum of the TotRmRate of the child records into the AVTotal textbox control in the parent subform?


Any suggestions are greatly appreciated.


If you know how I can attach a screen shot pleases advise.




I'm having problem with some Row Groups in a Matrix.

I have the following group hierarchy:


   Channel (as in where my products are sold)

   Category (as in what Category the specific product is

      Category/Channel (as in how much a category is sold in which channel)

      MerchandiseGroup (what merchandise group my product belongs to)

         MerchandiseGroup/Channel (you kinda get the picture here)


            ProductGroup/Channel (yep the same as before)


Now ... every ProductGroup has an Amount, the amount sold. So ... to show the amount sold of each group in my dataset I have a column for each group and the ProductGroup/Channel beeing the last of them.

Cat/Channel ... MerGrp/Channel and PG/Channel are created in the dataset as Select ... blablabla , Category + ' ' + Channel AS 'CatChannel' ... and so on for the other 2. But every row i nthe dataset has the correct Amount.

So ... in the Data fields I have ... =Sum(Fields!Amount.Value)

And here comes my problem:

It works for the following rows ... groups:

Total - OK

   Channel - OK

   Category - OK

      Category/Channel - EMPTY ... ??????

      MerchandiesGroup - OK

         MerchandiseGroup/Channel - EMPTY ... ??????

         ProductGroup - OK

            ProductGroup/Channel - OK ... ?????? why here and not the others?

So what I tried to do is to delete the child groups and kept Cat/Channel ... and then this group show the correct Sum(Fields!Amount.Value) ...

If I delete up to MerGrp/Channel ... then neither of them shows anything.


What am I doing wrong?


Thanks in advanced!!




I am trying to get a field in a child list to default to the value of the selected parent list item in Sharepoint 2010.  I have created a parent list called Order History to contain a list of orders.  The child list is called order history details.  This will hold the individual items that make up a particular order. 

I created a site page that has two web parts, one for the Plan History and one for the History Detail.  A data connection between the two adds the functionality that the history detail is filtered to only show items related to the selected parent item based on the 'orderid' field.  That is all great.

What I want -- when the user clicks to create a new history detail, the 'orderid' field should default to the selected field of the Order History item that is currently selected.  Right now there is a lookup column that lists only the orders that exist; i just can 't figure out how to set the default.

Anyone?  thank you in advance

I am trying to set up a parent child relationship using SPD but instead of using the ID like most tutorials recommend, I want to use a text-based field for the filter parameter. Any idea if this is possible and if it is what parameter source would I use to perform this action?

I have the following parent child relationship Employee > Employee Address with the relationship being 1 : n. I want to update the employee information as well as employee address at the same time. I am presently able to achieve this using the following code



EntityCollection<EmployeeAddress> address = new System.Data.Objects.DataClasses.EntityCollection<EmployeeAddress>();



newEmployeeAddress { Id = 10, EmployeeId = 33, Line1 = "Modified Line 1" });

emp =


newEmployee() { Id = 33, Name = "ABC", Age = 50};




newEmployee { Id = emp.Id });



newEmployeeAddress { Id = address.First().Id });




I have to perform two different operations to save the parent and child record. Is there any other efficient / better way to do this? I had a look at the sample code (One2ManyClass.cs file) of the All-In-One Code Framework http://1code.codeplex.com/ but could not find any relevant sample for the above scenario. I am presently in the EF learning phase. Any help on this will be highly appreciated. 





Hi Al,

Is there a way to create a contact form that takes the name. address and other info for the master record; Then, somehow, on the same page, allow the user to enter multiple contact info as chid records (i.e. phone, email, etc.)

All this using the Objec DataSource or SQL DataSource (which ever is easy) and doesn't require writing too much code.

Any reference material welcomed.




I'm using POCO template with Proxy based Change Tracking .

My parent entity (system_user) has '1 to *' relation to child entity (system_userSession).

And both entity have INSERT/UPDATE/DELETE stored procedure mappings.

public system_user GetUserWithActiveSession(string SessionToken)
  var users = from u in _context.system_people.OfType<system_user>()
        where u.userSessions.Any(us => us.token == SessionToken)
        select new
          userSessions = from us in u.userSessions
                  where us.token == SessionToken
                  select us

  return users.AsEnumerable().Select(o => o.u).FirstOrDefault();

public void UpdateUserSession(int Id, DateTime ExpiredOn)
  var session = (from us in _context.system_userSessions where us.id == Id select us).FirstOrDefault();
  if (session != null)
    session.expiredOn = ExpiredOn;

system_user user = GetUserWithActiveSession(_token);
system_userSession session = user.userSessions.FirstOrDefault();
UpdateUserSession(session.id, DateTime.Now);

Checking with SQL server profiler, it seems update stored procedure for system_user entity always called before calls to system_userSession update sp.

As you can see, i don't change system_user at all. How to avoid this ?



 I am woking on webapplication using .Net 3.5. I am loading page dynamically using IFRAM. page contains GridView and implemented as AutoGenerateSelectButton. when user select select button ion gridview, Populating child window uasing Javascript from codebehind.


I am facing problem is, when i update data in child window, Parent window gridview need to be refresh.

How can i overcome this problem. Can any one help me.

this.GetType(), "TestWindow", "<script language=\"javascript\">window.open('Test.aspx?TestID=" + TestID + "','','width=1100,height=850,left=100,top=100');</script>");


N.Srikanth Reddy


Hi, I have a parent and child entity as follows:

Parent: Contact

Child: Course (Custom Entity)

Relationship is N:1 Contact could subscribe to more than one Courses. The course entity has an attribute Fees (datatype is money). On Contact entity there is a custom attribute of TotalFees.

The TotalFees attribute on Contacts entity should display the total fees of all the courese subscribed by the Contact. e.g.

In a Gym the Contact has subscribed to Yoga (Fees 100) and Aerobics (Fees 200). The total of fees should be displayed and updated in the TotalFees attribute of the Contact entity whenever a record in Course entity is created, updated or deleted.

Please guide me how this can be accomplished through plug-in under the following cases.

Record is Created: How to know what is the contactid for which the TotalFees will be updated.

Update and Delete: How to update the TotalFees value from the plug-in. How to know the contactID from plug-in

For which entity the plug-in should be registered and for what events and stages e.g. Pre-create, post-create of contact/course. etc.





I have a display view for parent list.I also add data view for child list on the same display form and filtered the data view on parent list id, below the data view i added a link for Add New Form for child list.I am trying to send a parent Id to the Add new Form for child list using query string but can not get the id of Parent list.

As I noticed that display form does not contain the Id column. is that is the reason i am not getting id ?

is there  any other solution for this?



how to populate treeview  with a child node and with all its parent nodes





       -----a11 // if selected i want to draw treeview with its all parents







I really hope you can help me with this - I have tried to solve this for several days now. It concerns the Sharepoint 2010 platform.

It is pretty simple actually. I have created a parent/child webpart relationship, and it works pretty well. However, when I add a new child item I would like the child item to automatically relate to the chosen parent.

The ideal would be this scenario:

A Form with with task-details and a list of persons and hours at the bottom of the form, with a new "Add hours" button.

Hope somebody can help.

Best regards....


1] My SharePoint server and ASP.NET application servers are on different machines

2] In SharePoint I have excel file stored on document space. I have requirment where User will A] login to ASP.NET website B] On one web form user have link to open Excel sheet file which is stored in SharePoint (this sharepoint is on another machine)

3] Excel sheet file from SharePoint should be opened

4] User will update few columns with new data and Save the file

5] This Excel Sheet should be updated in SharePoint and the new updated values must be stored in different SQL Server database table


1] Is there a way that I can use SharePoint Excel web Service to directly open this Excel file from SharePoint? So that when I will update and save this file directly SharePoint excel file will be updated.

2] How can I read and save updated excel sheet file values into different sql server?




We need after event user fired (change at dataContext object) uptade all values binded to datacontext on controls descendant of grid control

¿Its is possible?



How can we know the parent-child relationship between workitems through API?

I can get the RelatedLink from LinkCollection but how do we know which workitem is parent and which one is child


I am having difficulty getting the correct results using TSQL

I have a parent table, primary key -> Parent.Id and a child table related by Child.Parent_Id

The child table contains keywords.

I want to get only the parents back that have an exact match on the keywords.

I tried the query...

select Parent_Id from child where child.keyword in ('one' 'two', 'three') group by parent_id having count(distinct keyword = 3)

This does not work if there are more than three .. For example a parent will be returned if it has ('one' 'two', 'three', 'four')

What can I do?






<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure