Click here to Skip to main content
15,905,563 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI

I have problem to insert records on table through linq to entities, where two tables are connected with foreign key.

My first table is


SQL
CREATE TABLE [dbo].[Emp](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[EmpName] [varchar](50) NULL,
 CONSTRAINT [PK_Emp] 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]


and second table is


SQL
CREATE TABLE [dbo].[EMpSecond](
	[Id] [int] NOT NULL,
	[EmpAge] [int] NULL
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[EMpSecond]  WITH CHECK ADD FOREIGN KEY([Id])
REFERENCES [dbo].[Emp] ([Id])


my insertion C# code is

C#
Emp emp = new Emp();
            emp.EmpName = txtName.Text;
            emp.Id = Convert.ToInt32(txtId.Text);

            EMpSecond sec = new EMpSecond();
            sec.EmpAge = Convert.ToInt32(txtAge.Text);
            sec.Id = Convert.ToInt32(txtId.Text);
            //sec.Emp.Id = emp.Id;

            using (TestEntities testEntities = new TestEntities())
            {
                testEntities.AddToEmps(emp);
                testEntities.SaveChanges();

                testEntities.AddToEMpSeconds(sec);
                testEntities.SaveChanges();
            }


please give me solution, its urgent
Posted
Updated 22-Nov-13 6:22am
v2
Comments
MTProgrammer 22-Nov-13 17:04pm    
Would be nice if you stated what the outcome of your existing code is/does...

1 solution

Emp emp = new Emp();
            emp.EmpName = txtName.Text;
            emp.Id = Convert.ToInt32(txtId.Text); // this should not be user enterable, ID's are generated by DB
 
            EMpSecond sec = new EMpSecond();
            sec.EmpAge = Convert.ToInt32(txtAge.Text);
            sec.Id = Convert.ToInt32(txtId.Text);
            //sec.Emp.Id = emp.Id;

            using (TestEntities testEntities = new TestEntities())
            {
                testEntities.AddToEmps(emp);
                testEntities.SaveChanges();
// once the save occurs, then the emp.Id will be populated after saveChanges() called
 sec.Id = emp.Id; // this line sets the sec.Id to the newly created ID when emp was added to DB.
                testEntities.AddToEMpSeconds(sec);
                testEntities.SaveChanges();
            }
 
Share this answer
 
Comments
Dharmendra-18 23-Nov-13 11:32am    
it gives error on the line testEntities.SaveChanges();// on Empseconds

Unable to update the EntitySet 'EMpSecond' because it has a DefiningQuery and no <insertfunction> element exists in the <modificationfunctionmapping> element to support the current operation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900