0% found this document useful (0 votes)
409 views

Linq Cheat Sheet

This document contains code snippets demonstrating various LINQ queries for a database context and customer table, including: 1) Creating a data context and database if it doesn't exist. 2) Examples of select, insert, update and delete queries. 3) More complex queries with filtering, paging, joining, grouping, aggregation and projections. 4) Attributes for mapping classes and properties to database tables and columns.

Uploaded by

Pedro Cachaco
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
409 views

Linq Cheat Sheet

This document contains code snippets demonstrating various LINQ queries for a database context and customer table, including: 1) Creating a data context and database if it doesn't exist. 2) Examples of select, insert, update and delete queries. 3) More complex queries with filtering, paging, joining, grouping, aggregation and projections. 4) Attributes for mapping classes and properties to database tables and columns.

Uploaded by

Pedro Cachaco
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

!"#$%&'%($!%)*%+, !

"#$%&'"##%
Data context & database create

!""#$%%&'()*+,-./(

var db = new MyDataContext(@"server=.\SQLEXPRESS;database=my;integrated security=SSPI"); if (!db.DatabaseExists()) db.CreateDatabase();

Select one
var only = db.Customers.SingleOrDefault(c => c.CustID == "CHIPS"); var first = db.Customers.FirstOrDefault(c => c.CustID == "CHIPS");

Insert
var customer = new Customer() { CustID = "CHIPS", CompanyName = "Mr. Chips" }; db.Customers.InsertOnSubmit(customer); db.SubmitChanges();

Where, null, contains & type


var r = new string[] { "WA", "OR" }; var customers = from c in db.Customers where c is Customer && (c.Region==null || r.Contains(c.Region)) select c;

Update
customer.ContactName = "Adam"; customer.Location = null; db.SubmitChanges();

Paging & order


var page3 = (from c in db.Customers orderby c.ContactName, c.City descending select c).Skip(10).Take(5);

Delete
db.Customers.DeleteOnSubmit(customer); db.SubmitChanges();

Class/table attributes Join, shape & distinct


var labels = (from c in db.Customers join o in db.Orders on c.CustID equals o.CustID select new { name = c.ContactName, address = o.ShipAddress }).Distinct(); [Table(Name="dbo.Customers")] [InheritanceMapping(Code="C", Type=typeof(Customer), IsDefault=true)] [InheritanceMapping(Code="T", Type=typeof(TopCustomer)]

Property/column attributes
[Column(Storage="_CustomerID", DbType="Int NOT NULL", Name="custid", IsPrimaryKey=true)] [Column(Storage="_Category", DbType="Char(1)", IsDiscriminator=true)] [Column(Storage="_Ver", IsVersion=true AutoSync=AutoSync.Always, UpdateCheck=UpdateCheck.Never, DbType="rowversion NOT NULL", CanBeNull=false, IsDbGenerated=true)]

Group, count, sum & projection


var totals = from c in db.Customers group c by c.Country into g select new Summary { Country = g.Key, CustomerCount = g.Count(), OrdCount = g.Sum(a=> a.Orders.Count)};

Composite & outer join


var r = from c in db.Customers join o in db.Orders on new { c=c.CustID, r=c.Country } equals new { c=o.CustID, r=o.ShipCountry } into j from jo in j.DefaultIfEmpty() select new { c, jo };

Association/relationship attributes
[Association(Name="Country_Customer", Storage="_Country", ThisKey="CoID", IsForeignKey=true)]

!"#$%&'%($!%)*%-./#0& !"#$%&'"##%
Data context & database create

!""#$%%&'()*+,-./(

Dim db = New MyDataContext("server=.\SQLEXPRESS;database=my;integrated security=SSPI") If Not db.DatabaseExists Then db.CreateDatabase()

Select one
Dim only = db.Customers.SingleOrDefault( Function(c) c.CustID = "CHIPS") Dim first = db.Customers.FirstOrDefault( Function(c) c.CustID = "CHIPS")

Insert
Dim customer = New Customer() With { .CustID = "CHIPS", .CompanyName = "Mr. Chips" } db.Customers.InsertOnSubmit(customer) db.SubmitChanges()

Where, null, contains & type


Dim r = New String() {"WA", "OR"} Dim customers = From c In db.Customers _ Where TypeOf c Is Customer AndAlso _ (c.Region Is Nothing OrElse _ r.Contains(c.Region)) Select c

Update
customer.ContactName = "Adam" customer.Location = Nothing db.SubmitChanges()

Paging & order


Dim page3 = From c In db.Customers _ Order By c.ContactName, c.City _ Descending Skip 10 Take 5 Select c

Delete
db.Customers.DeleteOnSubmit(customer) db.SubmitChanges()

Class/table attributes Join, shape & distinct


Dim labels = From c In db.Customers _ Join o in db.Orders _ On c.CustID Equals o.CustID _ Select name = c.ContactName, _ address = o.ShipAddress _ Distinct <Table(Name:="dbo.Customers")> _ <InheritanceMapping(Code:="C",Type:=_ GetType(Customer),IsDefault:=True)> _ <InheritanceMapping(Code="T", Type:=GetType(TopCustomer)> _

Property/column attributes
<Column(Storage:="_CustomerID", _ DbType:="Int NOT NULL", Name:="custid",_ IsPrimaryKey:=True)> _ <Column(Storage:="_Category", _ DbType:="Char(1)", _ IsDiscriminator:=True)> _ <Column(Storage:="_Ver", IsVersion:=True _ AutoSync:=AutoSync.Always, _ UpdateCheck:=UpdateCheck.Never, _ DbType:="rowversion NOT NULL", _ CanBeNull:=False, IsDbGenerated:=True)>_

Group, count, sum & projection


Dim totals = From c In db.Customers _ Group c By c.Country Into g = Group _ Select New Summary With _ {.Country = Country,.CustomerCount = _ g.Count(),OrdCount = g.Sum(Function(a) _ a.Orders.Count)}

Composite & outer join


Dim z = From c In db.Customers _ Group Join o In db.Orders On _ New With {.c=c.CustID,.r=c.Country} _ Equals New With _ {.c =o.CustID,.r =o.ShipCountry} _ Into j = Group _ From jo In j.DefaultIfEmpty() _ Select New With {c, jo}

Association/relationship attributes
<Association(Name:="Country_Customer", _ Storage:="_Country", ThisKey:="CoID", _ IsForeignKey:=True)> _

You might also like