使用Linq插入新数据 - WCF数据服务(以前称为ADO.NET数据服务)

Jam*_*mie 6 c# linq entity-framework-4 wcf-data-services

我真的很难将一些数据插入到2个数据库表中.

我正在使用实体框架4使用Linq而不是WCF数据服务.

这两个表看起来像这样:

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;
Run Code Online (Sandbox Code Playgroud)

每位员工必须只有一个帐户.但是,帐户可能根本没有任何员工.

我已经生成了实体,并公开了一个使用宽松访问规则设置的DataService:

config.SetEntitySetAccessRule( "Accounts" , EntitySetRights.All );
config.SetEntitySetAccessRule( "Employees" , EntitySetRights.All );
Run Code Online (Sandbox Code Playgroud)

使用LinqPad我可以成功插入一个帐户行,如下所示:

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

我可以从SQL Server看到已插入行,LinqPad报告没有错误.

问题是当我尝试同时插入相关的帐户和员工行时.

我确定下面的代码应该有用吗?

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();
Run Code Online (Sandbox Code Playgroud)

我从服务器返回的响应(启用了详细错误)基本上说:

Account row inserted successfully (HTTP 201)
Employee row did not insert (HTTP 500)
Run Code Online (Sandbox Code Playgroud)

完整的错误是:

'DbContainer.Employees'中的实体参与'EmployeeAccount'关系.找到0个相关的"帐户".1'账户'是预期的.

有没有人有一个适用于WCF数据服务的例子?

Fan*_*rns 7

对于阅读此内容的任何人来说,解决方案是在SaveChanges()之前添加以下行

context.SetLink(employee, "Account", account);
Run Code Online (Sandbox Code Playgroud)

简单地将帐户分配给员工是不够的,还需要建立一个链接.

  • 这是WCF数据服务**应该为我们做的事情**因为**在所有情况下**你必须在关联两个实体后调用`SetLink`. (2认同)