自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

淺析Linq插入數(shù)據(jù)的實(shí)現(xiàn)方法

開發(fā) 后端
今天用Linq插入數(shù)據(jù),總是插入錯誤,說某個主鍵字段不能為空,我檢查了半天感覺主鍵字段沒有賦空值啊,實(shí)在是郁悶。但最終還是解決了,拿來和大家分享。

Linq插入數(shù)據(jù)是一項(xiàng)基本的操作,雖然很基本,但是在操作的時候還是避免不了出現(xiàn)一些問題,現(xiàn)在我們就來看一個典型問題的解決辦法。

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

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

  1. create table RSSFeedRight    
  2. (    
  3. FeedId int Foreign Key (FeedId) References RSSFeed(FeedId) NOT NULL , -- FeedId , 
  4. UserId int Foreign Key (UserId) References UserInfo(UserId) NOT NULL , -- UserId ,   
  5. RightValue bigint NOT NULL Primary key (UserId, FeedId),   
  6. )  

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

  1. RSSFeedRight feedRight = new RSSFeedRight();   
  2. feedRight.UserId = userId;    
  3. feedRight.FeedId = feedId;    
  4. feedRight.RightValue = 0 ;    
  5. _Db.RSSFeedRights.InsertOnSubmit(feedRight);    
  6. _Db.SubmitChanges();  

每次Linq插入數(shù)據(jù)時都提示說FeedId 不能插入空值,郁悶的不行,分明是給了非空值的!

后來仔細(xì)檢查,發(fā)現(xiàn)這個RSSFeedRight 實(shí)體類中居然還有兩個指向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)進(jìn)行如下修改:

  1. create table RSSFeedRight  
  2. (   
  3. Id int identity ( 1 , 1 ) NOT NULL Primary Key ,   
  4. FeedId int Foreign Key (FeedId) References RSSFeed(FeedId) NOT NULL , -- FeedId ,   
  5. UserId int Foreign Key (UserId) References UserInfo(UserId) NOT NULL , -- UserId ,  
  6. RightValue bigint NOT NULL ,  
  7. )  

Linq插入數(shù)據(jù)問題解決。如此看來,老兵會遇到新問題,技術(shù)不經(jīng)常更新就要老化。

【編輯推薦】

  1. 簡單解決Linq多條件組合問題
  2. 將數(shù)據(jù)源進(jìn)行Linq排序
  3. Ordering方法實(shí)現(xiàn)Linq排序
  4. 輕輕松松學(xué)習(xí)Linq排序
  5. 詳解Linq聯(lián)合查詢表結(jié)果集的返回
責(zé)任編輯:阡陌 來源: 路由網(wǎng)
相關(guān)推薦

2009-12-23 09:04:41

LINQ通用分頁

2009-09-14 16:29:39

LINQ嵌套

2009-09-14 19:14:51

LINQ動態(tài)查詢

2009-09-15 23:21:17

Linq插入數(shù)據(jù)

2009-09-14 09:46:00

LINQ to SQL

2009-09-14 18:23:59

LINQ嵌套查詢

2009-09-17 10:57:06

Linq隨機(jī)讀取數(shù)據(jù)

2009-09-14 19:55:03

LINQ事務(wù)處理

2009-09-13 21:52:16

LINQ字符串

2009-09-15 14:30:11

Linq連接

2009-09-17 17:34:23

linq to sql

2009-09-14 19:20:22

LINQ TO SQL

2009-09-14 10:45:33

LINQ刪除數(shù)據(jù)

2009-09-18 14:25:36

LINQ to SQL

2009-09-17 13:30:32

LINQ to XML

2009-09-10 18:02:23

LINQ to SQL

2009-09-14 16:46:15

LINQ to XML

2009-09-16 17:11:35

LINQ To SQL

2009-09-16 15:33:22

LINQ to XML

2009-09-07 16:44:28

Linq String
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號