我正在尝试使用LINQ将记录插入到子表中,并且我收到"指定的强制转换无效"错误,该错误与所涉及的密钥有关.堆栈跟踪是:
消息:指定的强制转换无效.
类型:System.InvalidCastException源:System.Data.Linq TargetSite:Boolean TryCreateKeyFromValues(System.Object [],V ByRef)HelpLink:null Stack:at System.Data.Linq.IdentityManager.StandardIdentityManager.SingleKeyManager
2.TryCreateKeyFromValues(Object[] values, V& v) at System.Data.Linq.IdentityManager.StandardIdentityManager.IdentityCache2.Find(Object [] keyValues)在System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type,Object [] keyValues)处于System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type,Object [] keyValues)at at系统.Data.Linq.ChangeProcessor.BuildEdgeMaps()的System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc,Object实例)位于System.Data.Linq.DataContext的System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) System.Data.Linq.DataContext.SubmitChanges()中的.SubmitChanges(ConflictMode failureMode)(.....)
以下代码抛出此错误:
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
Run Code Online (Sandbox Code Playgroud)
有问题的表格在两者之间具有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')
Run Code Online (Sandbox Code Playgroud)
对同一个类的更新正常工作.例如
codebookVersion.ResponseCodes[0].Description = "BlahBlahBlah";
db.SubmitChanges(); //no exception - change is committed to db
Run Code Online (Sandbox Code Playgroud)
我在.Add()操作之后检查了变量rc,它确实收到了正确的responseCodeTableId,正如我所期望的那样,因为我将它添加到该集合中.
tblResponseCodeTable's full definition:
COLUMN_NAME TYPE_NAME
id int identity
responseCodeTableId int
surveyQuestionName nvarchar
code smallint
description nvarchar
dtCreate smalldatetime
Run Code Online (Sandbox Code Playgroud)
dtCreate的默认值为GetDate().
我能想到的另一个有用的信息就是没有SQL对数据库进行过尝试,所以LINQ在它尝试之前就会爆炸(因此错误不是SqlException).我已经分析并验证了没有尝试在数据库上执行任何语句.
当你和非PK领域有关系时,我已经阅读并看到了问题,但这不适合我的情况.
任何人都可以为我解释这种情况吗?我在这里错过了什么令人难以置信的事情?
非常感谢.
Paul Prewett
ResponseCode rc = new ResponseCode()
{
SurveyQuestionName = "Q11",
Code = 3,
Description = "Yet another code"
};
Run Code Online (Sandbox Code Playgroud)
和:
INSERT INTO tblResponseCode
(responseCodeTableId, surveyQuestionName, code, description)
VALUES (13683, 'Q11', 3, 'Yet another code')
Run Code Online (Sandbox Code Playgroud)
不一样,你没有传入外键引用。现在,我对 LINQ2SQL 很陌生,但我敢打赌 LINQ2SQL 不够聪明,无法为您做到这一点,它期望它作为匿名字典的第一个参数,并试图将字符串转换为整数。
只是一些想法。