开发者

Using LINQ to SQL to update database?

When I execute the following code I don't get any error, but it doesn't update the changes on the database either. I have 5 entries in the table user, and after executing the following code there is no user with "Active" state in the database.

Am I supposed to write the update statement myself or does it do it for me? What can be the problem here?

var dbContext = new DataClasses1DataContext();

List<user> users = (from u in dbContext.users
                          where u.age < 30
                          select u).ToList();

users[0].state = "Active";
dbContext.SubmitChanges();

EDIT:

So I know what the problem is. I change the State on my object, and the update statement contains the state as a where clause. So when executing the query it can't find an item that matches - it fails on [state] = @p4.

Why is it using all parameters in my update statement when I have a primary key?

UPDATE [dbo].[user]
SET [state] = @p5
WHERE ([id] = @p0) AND ([firstName] = @p1) AND ([lastName] = @p2) 
    AND ([age] = @p3) AND ([state] = @p4)
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
-- @p1: Input NChar (Size = 10; Prec = 0; Scale = 0) [firstName   开发者_开发技巧  ]
-- @p2: Input NChar (Size = 10; Prec = 0; Scale = 0) [lastName  ]
-- @p3: Input Int (Size = -1; Prec = 0; Scale = 0) [25]
-- @p4: Input NChar (Size = 10; Prec = 0; Scale = 0) [Active    ]
-- @p5: Input NChar (Size = 10; Prec = 0; Scale = 0) [Active]


You need to change the concurrency pattern on your DBML. This website about Updating LINQ-to-SQL entities explains a bit about it.

Anything you don't want to include in the WHERE clause should have their Update Check set to Never on the DBML.

  • Open DBML
  • Select the state property on your user object
  • Press F4 (to see properties)
  • Change Update Check (the last setting in the properties) to Never
  • Save and try again

Normally I'd turn off Update Check for all columns but you should do more reading to understand exactly how it works in case you need concurrency.


Apparently, you don't have a primary key on the user table or you didn't specify it in your dbml file. LINQ to SQL only throws exceptions when you insert or delete a record with no primary key. It doesn't throw an exception when updating for some reason.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜