Dharmendra Singh

Dharmendra Singh

  • NA
  • 119
  • 48.4k

Linq to Entities Insert, Delete on Foreign key relation

Nov 25 2013 6:27 AM
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
 
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
 

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

Emp emp = new Emp();
emp.EmpName = txtName.Text;  
EMpSecond sec = new EMpSecond();
sec.EmpAge = Convert.ToInt32(txtAge.Text);
 //sec.Emp.Id = emp.Id;
using (TestEntities testEntities = new TestEntities())
 {
testEntities.AddToEmps(emp);
 testEntities.SaveChanges();  

sec.Id=emp.Id;
testEntities.AddToEMpSeconds(sec);
testEntities.SaveChanges();
}

it gives error on the line testEntities.SaveChanges();// on Empseconds Unable to update the EntitySet 'EMpSecond' because it has a DefiningQuery and no element exists in the element to support the current operation.

please give me solution, its urgent

Answers (2)