Linq to SQL 插入數(shù)據(jù)時的一個問題
發(fā)布日期:2022-01-31 15:12 | 文章來源:源碼中國
復(fù)制代碼 代碼如下:
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)有不少人遇到相同問題
找到其中一篇帖子
http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/e14f76ec-0ffe-4dd1-893c-6a4c8440c54a
其中關(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)進行如下修改
復(fù)制代碼 代碼如下:
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 ,
)
問題解決。
老兵遇到新問題,技術(shù)不經(jīng)常更新就要老化。
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章