溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Linq插入數(shù)據(jù)問題怎么解決

發(fā)布時間:2021-12-02 09:46:35 來源:億速云 閱讀:145 作者:iii 欄目:編程語言

這篇文章主要講解了“Linq插入數(shù)據(jù)問題怎么解決”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Linq插入數(shù)據(jù)問題怎么解決”吧!

今天用Linq插入數(shù)據(jù),總是插入錯誤,說某個主鍵字段不能為空,我檢查了半天感覺主鍵字段沒有賦空值啊,實在是郁悶。

要插入數(shù)據(jù)的表結(jié)構(gòu)是:

create table RSSFeedRight  (  FeedId int Foreign Key (FeedId) References RSSFeed(FeedId) NOT NULL , -- FeedId ,   UserId int Foreign Key (UserId) References UserInfo(UserId) NOT NULL , -- UserId ,   RightValue bigint NOT NULL Primary key (UserId, FeedId),  )

插入數(shù)據(jù)的代碼:

RSSFeedRight feedRight = new RSSFeedRight();  feedRight.UserId = userId;  feedRight.FeedId = feedId;  feedRight.RightValue = 0 ;   _Db.RSSFeedRights.InsertOnSubmit(feedRight);  _Db.SubmitChanges();

每次插入時都提示說FeedId 不能插入空值,郁悶的不行,分明是給了非空值的!

后來仔細檢查,發(fā)現(xiàn)這個RSSFeedRight 實體類中居然還有兩個指向UserInfo 和 RSSFeed 表的字段,后來逐漸感覺到是外鍵設(shè)置問題引起的。立即通過google 搜 "linq foreign key insert",發(fā)現(xiàn)有不少人遇到相同問題,找到其中一篇帖子,其中關(guān)于這個問題是這樣描述的:

The mapping information (Assocation attribute on Table1 & Table2) has the foreign key dependency going in the wrong direction. It's claiming that the primary-key in table1 (the one that is auto-incremented) is a foreign key to the primary key in table2. You want that just the opposite. You can change this in the designer, DBML file or directly in the code (for a quick test) by changing IsForeignKey value for both associations.

也就是說我們不能將主鍵設(shè)置為和外鍵相同,否則就會出問題。找到問題所在,就好辦了,將表結(jié)構(gòu)進行如下修改:

create table RSSFeedRight  (  Id int identity ( 1 , 1 ) NOT NULL Primary Key ,  FeedId int Foreign Key (FeedId) References RSSFeed(FeedId) NOT NULL , -- FeedId ,   UserId int Foreign Key (UserId) References UserInfo(UserId) NOT NULL , -- UserId ,   RightValue bigint NOT NULL ,  )

感謝各位的閱讀,以上就是“Linq插入數(shù)據(jù)問題怎么解決”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對Linq插入數(shù)據(jù)問題怎么解決這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI