简体   繁体   中英

Deleting records in LINQ with foreign keys - invalid cast exception

I have a simple database:

ARTICLE
----------
ArticleId (PK),
ArticleTitle
..other stuff...

USER-ARTICLE
------------
ArchiveId (PK),
UserId,
ArticleId
..other stuff...

The articleId 's are foreign keys.

I want to be able to delete a user article row by UserArticleId using the following code,

UserArticle myobjtodelete = PersonalArchiveDb.UserArticles.Single(ua => ua.ArchiveId == 3);
PersonalArchiveDb.UserArticles.DeleteOnSubmit(myobjtodelete);
PersonalArchiveDb.SubmitChanges();

(Yes I'm aware I can do the statement inside the delete rather than retrieving the object, it was for debugging purposes to make sure the object definitely exists - it does.)

When the debugger hits the SubmitChanges() line, I get a runtime error:

Specified cast is not valid.

Here is the stack trace,

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() at Driver_SOC_ASO.Controls.PersonalArchive.ArchiveListing.grdArchive_RowDeleting(Object sender, GridViewDeleteEventArgs e) in C:\\work\\Driver.Net\\Driver-SOC-ASO\\Driver-SOC-ASO\\Controls\\PersonalArchive\\ArchiveListing.ascx.cs:line 78 at System.Web.UI.WebControls.GridView.OnRowDeleting(GridViewDeleteEventArgs e) at System.Web.UI.WebControls.GridView.HandleDelete(GridViewRow row, Int32 rowIndex) at System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) at System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) at System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

I am at a loss, any ideas?

这可能是这个错误的一个例子,微软称这是在.NET 4.0中修复的。

在您的dbml中,检查是否存在关联不正确的文章和用户文章。

尝试为ArticleId设置ON CASCADE DELETE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM