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
Loading
Jignesh TrivediPosted Nov 26, 2013, 12:46 AM
hi,
If we defining foreign key between the tables than entity framework automatically create the relation between these tables and relation may be many to many, many to one or one to one.
also you need not add foreign key id to other table (empsec in your case).
what type of relation between these tables in you case?
if it is one to one than try...
Emp emp = new Emp();
emp.EmpName = txtName.Text;
EMpSecond sec = new EMpSecond();
sec.EmpAge = Convert.ToInt32(txtAge.Text);
using (TestEntities testEntities = new TestEntities())
{
emp.EMPSecond = sec;
testEntities.Emp.AddObject(emp);
testEntities.SaveChanges();
}
hope this will help you.
Jaganathan BantheswaranPosted Nov 25, 2013, 8:46 AM
Is there Emp property in sec object?
then try to set Emp to emp.