Insert new data using Linq - WCF Data Services (formerly ADO.NET Data Services)

I am really trying to insert some data into two database tables.

I am using Linq over WCF data services using Entity Framework 4.

2 tables look like this:

CREATE TABLE [dbo].[Accounts] ( [Id] int IDENTITY(1,1) NOT NULL, [Email] nvarchar(max) NOT NULL, [Password] nvarchar(max) NOT NULL ); CREATE TABLE [dbo].[Employees] ( [Id] int IDENTITY(1,1) NOT NULL, [Name] nvarchar(max) NOT NULL, [Role] nvarchar(max) NOT NULL, [Account_Id] int NOT NULL ); ALTER TABLE [dbo].[Employees] ADD CONSTRAINT [FK_EmployeeAccount] FOREIGN KEY ([Account_Id]) REFERENCES [dbo].[Accounts] ([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION; 

Each employee must have only 1 account. However, the Account may not have employees.

I created the objects and discovered a DataService that is configured using easy access rules:

 config.SetEntitySetAccessRule( "Accounts" , EntitySetRights.All ); config.SetEntitySetAccessRule( "Employees" , EntitySetRights.All ); 

Using LinqPad I can successfully insert one row of an account as follows:

 var context = this; Account account = Account.CreateAccount(1, " foo@example.com ", " p@ssword "); context.AddToAccounts(account); context.SaveChanges(); 

I see from SQL Server that the row is inserted, and LinqPad does not report an error.

The problem is that I'm trying to insert Account and Employee together as a related string.

I'm sure the code below should work?

 var context = this; Account account = Account.CreateAccount(1, " foo@example.com ", "password"); context.AddToAccounts(account); Employee employee = Employee.CreateEmployee(1, "Foo", "Developer"); employee.Account = account; context.AddToEmployees(employee); context.SaveChanges(); 

The answer I am returning from the server (with verbose errors enabled) basically says that:

 Account row inserted successfully (HTTP 201) Employee row did not insert (HTTP 500) 

Full error:

Entities in DbContainer.Employees participate in an EmployeeAccount relationship. 0 related "Account". Expected 1 "Account".

Does anyone have an example that works with WCF data services?

+6
c # linq entity-framework-4 wcf-data-services
source share
1 answer

For anyone reading this, the solution was to add the following line before SaveChanges ()

 context.SetLink(employee, "Account", account); 

Simply assigning an account to an employee was not enough; you also had to establish a link.

+7
source share

All Articles