Tuesday, November 11, 2008

Fun with LINQ: database programming tasks in under 10 lines of code

Go to Project->New Item->Data LINQ to SQL classes. After you get the design surface, click on "Server Explorer" (a tab on the right), connect to a database, and drag over tables to the white space in the middle of the screen.

Save the resulting DBML file.

Let's say the DBML file is called Snippets.dbml, and it contains the table People (note that below LINQ class generator converted it to plural "Peoples" - a bit annoying, but... whatever).

Simplest query - get everything:

SnippetsDataContext snippets = new SnippetsDataContext();
var allPeople = from person in context.Peoples
select person;
foreach(People person in allPeople)
{...}
snippets.Connection.Close();
snippets.Dispose();

A simple precondition:

SnippetsDataContext snippets = new SnippetsDataContext();
var activePeople = from person in context.Peoples
where person.IsActive
select person;
foreach(People person in activePeople)
{...}
snippets.Connection.Close();
snippets.Dispose();

A more complicated precondition:

SnippetsDataContext snippets = new SnippetsDataContext();
var activeMikes = from person in context.Peoples
where person.IsActive && person.Name.Contains("Mike")
select person;
foreach(People person in activeMikes)
{...}
snippets.Connection.Close();
snippets.Dispose();

Get only the data you need, with anonymous types:

SnippetsDataContext snippets = new SnippetsDataContext();
var peopleNamesAndIds = from person in context.Peoples
select new { person.PersonId, person.PersonName };
foreach(var p in peopleNamesAndIds)
{
Console.WriteLine(p.PersonId + ": " + p.PersonName);
}
snippets.Connection.Close();
snippets.Dispose();

Modifying data:

SnippetsDataContext snippets = new SnippetsDataContext();
var renameMikesToJohns = from person in context.Peoples
where person.Name.Contains("Mike")
select person;
foreach(People person in renameMikesToJohns)
{
person.PersonName = person.PersonName.Replace("Mike", "John");
}
context.SubmitChanges();
snippets.Connection.Close();
snippets.Dispose();

Adding a row:

SnippetsDataContext snippets = new SnippetsDataContext();
People person = new Person();
person.PersonName = "Bill Maher";
context.Peoples.InsertOnSubmit(person);

No comments: