浅析Linq插入数据的实现方法

开发 后端
今天用Linq插入数据,总是插入错误,说某个主键字段不能为空,我检查了半天感觉主键字段没有赋空值啊,实在是郁闷。但最终还是解决了,拿来和大家分享。

Linq插入数据是一项基本的操作,虽然很基本,但是在操作的时候还是避免不了出现一些问题,现在我们就来看一个典型问题的解决办法。

今天用Linq插入数据,总是插入错误,说某个主键字段不能为空,我检查了半天感觉主键字段没有赋空值啊,实在是郁闷。

要插入数据的表结构是:

  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插入数据的代码:

  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插入数据时都提示说FeedId 不能插入空值,郁闷的不行,分明是给了非空值的!

后来仔细检查,发现这个RSSFeedRight 实体类中居然还有两个指向UserInfo 和 RSSFeed 表的字段,后来逐渐感觉到是外键设置问题引起的。立即通过google 搜 "linq foreign key insert",发现有不少人遇到相同问题,找到其中一篇帖子,其中关于这个问题是这样描述的:

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.

也就是说我们不能将主键设置为和外键相同,否则就会出问题。找到问题所在,就好办了,将表结构进行如下修改:

  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插入数据问题解决。如此看来,老兵会遇到新问题,技术不经常更新就要老化。

【编辑推荐】

  1. 简单解决Linq多条件组合问题
  2. 将数据源进行Linq排序
  3. Ordering方法实现Linq排序
  4. 轻轻松松学习Linq排序
  5. 详解Linq联合查询表结果集的返回
责任编辑:阡陌 来源: 路由网
相关推荐

2009-12-23 09:04:41

LINQ通用分页

2009-09-14 19:14:51

LINQ动态查询

2009-09-14 16:29:39

LINQ嵌套

2009-09-15 23:21:17

Linq插入数据

2009-09-14 09:46:00

LINQ to SQL

2009-09-14 18:23:59

LINQ嵌套查询

2009-09-17 10:57:06

Linq随机读取数据

2009-09-14 19:55:03

LINQ事务处理

2009-09-13 21:52:16

LINQ字符串

2009-09-15 14:30:11

Linq连接

2009-09-14 19:20:22

LINQ TO SQL

2009-09-14 10:45:33

LINQ删除数据

2009-09-17 17:34:23

linq to sql

2009-09-18 14:25:36

LINQ to SQL

2009-09-13 20:28:38

Linq插入数据

2009-09-17 13:30:32

LINQ to XML

2009-09-16 15:33:22

LINQ to XML

2009-09-15 13:30:54

linq级联

2009-09-07 16:44:28

Linq String

2009-09-10 18:02:23

LINQ to SQL
点赞
收藏

51CTO技术栈公众号