Querying a Database—LINQ to SQL
One of the more interesting features of EF is that running SQL statements is very much like working with a collection. For example, say you want to retrieve a product by its name. You can get a product by name the same way you would be using LINQ:
public Product GetByName(string name) { Â Â Â Â var product = db.Products.FirstOrDefault(p => p.Name == name); Â Â Â Â return product; }
Here, FirstOrDefault
returns the first matching product by its name. If no product by that name exists, then it returns a null
.
What about finding a unique element by its ID? In that case, you would use a special method (Find
), which either gets an entity from a database or, if one with the same ID has been retrieved recently, returns it from memory:
public Product GetById(int id) { Â Â Â Â var product = db.Products.Find(id); Â Â Â Â return product; }
When using a primary key, it is better...