插入主键=外键
Insert with PrimaryKey=ForeignKey
我有两个表:
File
|- Id (Primary Key)
|- Name
|- ...
SpecificFile
|- FileId (Primary Key & Foreign Key to File.Id)
|- SpecificProperty1
|- ...
我有以下 Linq2Sql 代码 (LINQPad):
var sfiles = from f in File
where f.Name LIKE 'Specific%'
select new SpecificFile { FileId = f.Id, SpecificProperty1 = "Foo" };
SpecificFiles.InsertAllOnSubmit(sfiles);
但是,插入失败:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_SpecificFile_File". The conflict occurred in database "MyDatabase", table "dbo.File", column 'Id'.
The statement has been terminated.
如果我调试并查看 Linq2Sql 生成的 INSERT 语句,原因就很清楚了:
INSERT INTO [SpecificFile]([SpecificProperty1])
VALUES (@p0)
如何通知 Linq2Sql 它必须使用特定的 ID 进行插入?
注意:在 new
表达式中将 File
对象引用设置为 f
也无济于事。
自己找到了答案...不幸的是,SpecificFile.FileId 被设置为 IDENTITY(1,1)
。异常消息没有多大帮助...
我有两个表:
File
|- Id (Primary Key)
|- Name
|- ...
SpecificFile
|- FileId (Primary Key & Foreign Key to File.Id)
|- SpecificProperty1
|- ...
我有以下 Linq2Sql 代码 (LINQPad):
var sfiles = from f in File
where f.Name LIKE 'Specific%'
select new SpecificFile { FileId = f.Id, SpecificProperty1 = "Foo" };
SpecificFiles.InsertAllOnSubmit(sfiles);
但是,插入失败:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_SpecificFile_File". The conflict occurred in database "MyDatabase", table "dbo.File", column 'Id'. The statement has been terminated.
如果我调试并查看 Linq2Sql 生成的 INSERT 语句,原因就很清楚了:
INSERT INTO [SpecificFile]([SpecificProperty1])
VALUES (@p0)
如何通知 Linq2Sql 它必须使用特定的 ID 进行插入?
注意:在 new
表达式中将 File
对象引用设置为 f
也无济于事。
自己找到了答案...不幸的是,SpecificFile.FileId 被设置为 IDENTITY(1,1)
。异常消息没有多大帮助...