程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> Linq to SQL 插入數據時的一個問題

Linq to SQL 插入數據時的一個問題

編輯:關於SqlServer

代碼如下:

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),
)

插入數據的代碼

RSSFeedRight feedRight = new RSSFeedRight();
feedRight.UserId = userId;
feedRight.FeedId = feedId;
feedRight.RightValue = 0 ;
_Db.RSSFeedRights.InsertOnSubmit(feedRight);
_Db.SubmitChanges();
每次插入時都提示說FeedId 不能插入空值,郁悶的不行,分明是給了非空值的!
後來仔細檢查,發現這個RSSFeedRight 實體類中居然還有兩個指向UserInfo 和 RSSFeed 表的字段,後來逐漸感覺到是外鍵設置問題引起的。立即通過google 搜 "linq foreign key insert"
發現有不少人遇到相同問題
找到其中一篇帖子
http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/e14f76ec-0ffe-4dd1-893c-6a4c8440c54a
其中關於這個問題是這樣描述的
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.
也就是說我們不能將主鍵設置為和外鍵相同,否則就會出問題。找到問題所在,就好辦了,將表結構進行如下修改

代碼如下:

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 ,
)

問題解決。
老兵遇到新問題,技術不經常更新就要老化。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved