[英]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.