6
我非常努力地将一些数据插入到2个数据库表中。使用Linq插入新数据 - WCF数据服务(以前称为ADO.NET数据服务)
我使用实体框架4.
的2个表看起来像这样使用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;
每名员工必须仅有1帐户。但是,帐户可能根本没有任何员工。
我已经生成的实体,并露出了DataService的是建立以轻松访问规则:
config.SetEntitySetAccessRule("Accounts" , EntitySetRights.All);
config.SetEntitySetAccessRule("Employees" , EntitySetRights.All);
使用LinqPad我可以成功地插入一个单一账户行像这样:
var context = this;
Account account = Account.CreateAccount(1, "[email protected]", "[email protected]");
context.AddToAccounts(account);
context.SaveChanges();
我可以从SQL Server看到该行已被插入,并且LinqPad报告没有错误。
问题是,当我尝试将相关的帐户和员工行一起插入时。
我确定下面的代码应该可以工作吗?
var context = this;
Account account = Account.CreateAccount(1, "[email protected]", "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数据服务的例子?
不错的。之后预订,因为我确信当我开始使用一些WCF数据服务时,我会遇到这个问题。 – 2010-08-26 01:00:02
这是WCF数据服务**应该为我们**做的事情,因为在所有情况下**都必须在关联两个实体后调用SetLink。 – Yuck 2011-06-16 19:21:00
注意:如果在调用SetLink时收到“未被跟踪”异常,请确保调用'AddToMySource(mySource)'_before_调用'SetLink(mySource,“Property”,myTarget)'' – Pakman 2012-03-19 15:21:48