我正在尝试使用 LINQ 将记录插入到子表中
收到“指定的强制转换无效”错误,这与 w/
所涉及的键。堆栈跟踪是:
Message: Specified cast is not valid.
Type: System.InvalidCastException Source: 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.IdentityCache
2.Find(Object[] keyValues) at System.Data.Linq.IdentityManager.StandardIdentityManager.Find(MetaType type, Object[] keyValues) at System.Data.Linq.CommonDataServices.GetCachedObject(MetaType type, Object[] keyValues) at System.Data.Linq.ChangeProcessor.GetOtherItem(MetaAssociation assoc, Object instance) at System.Data.Linq.ChangeProcessor.BuildEdgeMaps() at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) at 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 领域有关系时,我已经阅读并看到了问题,但这不适合我的情况。
任何人都可以为我解释这种情况吗?我在这里错过了什么非常明显的事情?
非常感谢。
保罗·普威特
最佳答案
贴出父表的模式。
如果你看这里,其他人也遇到了你的问题。
http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3493504&SiteID=1
看起来 Linq2SQL 无法将一些外键映射到一些主键。一个人有一个解决方案,但我认为您已经映射到 IDENTITY 列。
关于LINQ 到 SQL -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/237415/