Linq to SQL 插入數(shù)據(jù)時的一個問題
更新時間:2009年08月29日 16:28:59 作者:
今天用LinqtoSql插入數(shù)據(jù),總是插入錯誤,說某個主鍵字段不能為空,我檢查了半天感覺主鍵字段沒有賦空值啊,實在是郁悶。
要插入數(shù)據(jù)的表結構是
復制代碼 代碼如下:
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 表的字段,后來逐漸感覺到是外鍵設置問題引起的。立即通過google 搜 "linq foreign key insert"
發(fā)現(xiàn)有不少人遇到相同問題
找到其中一篇帖子
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 ,
)
問題解決。
老兵遇到新問題,技術不經常更新就要老化。
相關文章
sql自動增長標識導致導入數(shù)據(jù)問題的解決方法
對于一個設了自動增長標識的數(shù)據(jù)表來說,它的字段的值是由數(shù)據(jù)庫自動設置的;這在導數(shù)據(jù)時很麻煩2012-11-11SQLServer行列互轉實現(xiàn)思路(聚合函數(shù))
這篇文章主要為大家詳細介紹了SQLServer行列互轉實現(xiàn)思路,使用聚合函數(shù)pivot/unpivot實現(xiàn)行列互轉,感興趣的小伙伴們可以參考一下2016-03-03SQL 尚未定義空閑 CPU 條件 - OnIdle 作業(yè)計劃將不起任何作用
今天在配置sql server 代理服務器的計劃任務的時候發(fā)現(xiàn)了日志中提示這個SQL 尚未定義空閑 CPU 條件 - OnIdle 作業(yè)計劃將不起任何作用信息導致無法執(zhí)行計劃任務,那么可以按照下面的方法解決即可2021-06-06sql復制表結構和數(shù)據(jù)的實現(xiàn)方法
這篇文章主要介紹了sql復制表結構和數(shù)據(jù)的實現(xiàn)方法,需要的朋友可以參考下2010-06-06SQL Server 提取數(shù)字、提取英文、提取中文的sql語句
這篇文章主要介紹了SQL Server 提取數(shù)字、提取英文、提取中文 ,需要的朋友可以參考下2014-10-10