淺析Linq插入數(shù)據(jù)的實(shí)現(xiàn)方法
Linq插入數(shù)據(jù)是一項(xiàng)基本的操作,雖然很基本,但是在操作的時(shí)候還是避免不了出現(xiàn)一些問(wèn)題,現(xiàn)在我們就來(lái)看一個(gè)典型問(wèn)題的解決辦法。
今天用Linq插入數(shù)據(jù),總是插入錯(cuò)誤,說(shuō)某個(gè)主鍵字段不能為空,我檢查了半天感覺(jué)主鍵字段沒(méi)有賦空值啊,實(shí)在是郁悶。
要插入數(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),
- )
Linq插入數(shù)據(jù)的代碼:
- RSSFeedRight feedRight = new RSSFeedRight();
- feedRight.UserId = userId;
- feedRight.FeedId = feedId;
- feedRight.RightValue = 0 ;
- _Db.RSSFeedRights.InsertOnSubmit(feedRight);
- _Db.SubmitChanges();
每次Linq插入數(shù)據(jù)時(shí)都提示說(shuō)FeedId 不能插入空值,郁悶的不行,分明是給了非空值的!
后來(lái)仔細(xì)檢查,發(fā)現(xiàn)這個(gè)RSSFeedRight 實(shí)體類(lèi)中居然還有兩個(gè)指向UserInfo 和 RSSFeed 表的字段,后來(lái)逐漸感覺(jué)到是外鍵設(shè)置問(wèn)題引起的。立即通過(guò)google 搜 "linq foreign key insert",發(fā)現(xiàn)有不少人遇到相同問(wèn)題,找到其中一篇帖子,其中關(guān)于這個(gè)問(wè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.
也就是說(shuō)我們不能將主鍵設(shè)置為和外鍵相同,否則就會(huì)出問(wèn)題。找到問(wèn)題所在,就好辦了,將表結(jié)構(gòu)進(jìn)行如下修改:
- 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ù)問(wèn)題解決。如此看來(lái),老兵會(huì)遇到新問(wèn)題,技術(shù)不經(jīng)常更新就要老化。
【編輯推薦】