Using LINQ, I updated the field Age of a Person object. When I looked at the generated SQL (from SQL Server Profiler), I saw the following.
Code:
exec sp_executesql N'UPDATE [dbo].[Persons]
SET [Age] = @p4
WHERE ([PersonId] = @p0) AND ([FirstName] = @p1) AND ([LastName] = @p2) AND ([Age] = @p3)',N'@p0 int,@p1 nvarchar(4),@p2 nvarchar(5),@p3 int,@p4 int',@p0=1,@p1=N'John',@p2=N'Smith',@p3=21,@p4=22
I was wondering why the WHERE clause has to include fields PersonId, FirstName, LastName, and Age when it could have just used the field PersonId. Is there a way to force LINQ to use primary key only?
I created database below.
Code:
CREATE TABLE dbo.Persons
(
PersonId INT NOT NULL IDENTITY PRIMARY KEY
, FirstName NVARCHAR(100) NOT NULL
, LastName NVARCHAR(100) NULL
, Age INT NOT NULL
)
INSERT INTO dbo.Persons
SELECT
FirstName = 'John'
, LastName = 'Smith'
, Age = 21
Then, I created the .dbml by drag-and-dropping the database to my project.
And here's is my program.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQ
{
class Program
{
static void Main(string[] args)
{
Entities.DataContext context = new Entities.DataContext();
int personId = 1;
Entities.Person person = context.Persons.SingleOrDefault(p => p.PersonId == personId);
person.Age = 22;
context.SubmitChanges();
}
}
}