我正在尝试使用 LINQ 将记录插入到子表中,并且我
收到“指定的转换无效”错误,该错误与/有关
涉及的按键。堆栈跟踪是:
消息:指定的演员阵容无效。
类型:System.InvalidCastException
来源:System.Data.Linq 目标站点:
布尔值
TryCreateKeyFromValues(System.Object[],
V ByRef) HelpLink: null 堆栈: at
System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager2.TryCreateKeyFromValues(Object[]
values, V& v) at
System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache
2.查找(对象[]
键值)在
System.Data.Linq.IdentityManager.StandardIdentityManager.Find(元类型
类型,Object[] keyValues)位于
System.Data.Linq.CommonDataServices.GetCachedObject(元类型
类型,Object[] keyValues)位于
System.Data.Linq.ChangeProcessor.GetOtherItem(元关联
assoc,对象实例)位于
System.Data.Linq.ChangeProcessor.BuildEdgeMaps()
在
System.Data.Linq.ChangeProcessor.SubmitChanges(冲突模式
故障模式)在
System.Data.Linq.DataContext.SubmitChanges(冲突模式
故障模式)在
System.Data.Linq.DataContext.SubmitChanges()
(.....)
以下代码引发此错误:
ResponseDataContext db = new ResponseDataContext(m_ConnectionString);
CodebookVersion codebookVersion = db.CodebookVersions.Single(cv => cv.VersionTag == m_CodebookVersionTag);
ResponseCode rc = new ResponseCode()
{
SurveyQuestionName = "Q11",
Code = 3,
Description = "Yet another code"
};
codebookVersion.ResponseCodes.Add(rc);
db.SubmitChanges(); //exception gets thrown here
所讨论的表两者之间具有 FK 关系。
父表的列称为“id”,是 PK,类型为:INT NOT NULL IDENTITY
子表的列称为“responseCodeTableId”,类型为:INT NOT NULL。
codebookVersion(父类)映射到表 tblResponseCodeTable
responseCode (childClass) 映射到表 tblResponseCode
如果我直接执行SQL就可以了。例如
INSERT INTO tblResponseCode
(responseCodeTableId, surveyQuestionName, code, description)
VALUES (13683, 'Q11', 3, 'Yet another code')
对同一类的更新工作正常。例如
codebookVersion.ResponseCodes[0].Description = "BlahBlahBlah";
db.SubmitChanges(); //no exception - change is committed to db
我在 .Add() 操作之后检查了变量 rc,它确实收到了正确的 responseCodeTableId,正如我所期望的那样,因为我将其添加到该集合中。
tblResponseCodeTable's full definition:
COLUMN_NAME TYPE_NAME
id int identity
responseCodeTableId int
surveyQuestionName nvarchar
code smallint
description nvarchar
dtCreate smalldatetime
dtCreate 有一个默认值 GetDate()。
我能想到的唯一有用的信息是没有 SQL
曾经对数据库进行过尝试,所以 LINQ 在它之前就崩溃了
尝试(因此错误不是 SqlException)。我已经进行了分析和验证
没有尝试在数据库上执行任何语句。
当你与非 PK 领域有关系时,我已经阅读并看到了这个问题,但这不适合我的情况。
谁能帮我解释一下这种情况?我在这里错过了什么非常明显的事情?
非常感谢。
保罗·普威特