[英]Insert New Data using Linq — WCF Data Services (formerly ADO.NET 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;
每位员工必须只有一个帐户。 但是,帐户可能根本没有任何员工。
我已经生成了实体,并公开了一个使用宽松访问规则设置的DataService:
config.SetEntitySetAccessRule( "Accounts" , EntitySetRights.All );
config.SetEntitySetAccessRule( "Employees" , EntitySetRights.All );
使用LinqPad我可以成功插入一个帐户行,如下所示:
var context = this;
Account account = Account.CreateAccount(1, "foo@example.com", "p@ssword");
context.AddToAccounts(account);
context.SaveChanges();
我可以从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();
我从服务器返回的响应(启用了详细错误)基本上说:
Account row inserted successfully (HTTP 201)
Employee row did not insert (HTTP 500)
完整的错误是:
'DbContainer.Employees'中的实体参与'EmployeeAccount'关系。 找到0个相关的“帐户”。 1'账户'是预期的。
有没有人有一个适用于WCF数据服务的例子?
对于阅读此内容的任何人来说,解决方案是在SaveChanges()之前添加以下行
context.SetLink(employee, "Account", account);
简单地将帐户分配给员工是不够的,还需要建立一个链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.