Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The C# Workshop

You're reading from   The C# Workshop Kickstart your career as a software developer with C#

Arrow left icon
Product type Paperback
Published in Sep 2022
Publisher Packt
ISBN-13 9781800566491
Length 780 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (3):
Arrow left icon
Almantas Karpavicius Almantas Karpavicius
Author Profile Icon Almantas Karpavicius
Almantas Karpavicius
Jason Hales Jason Hales
Author Profile Icon Jason Hales
Jason Hales
Mateus Viegas Mateus Viegas
Author Profile Icon Mateus Viegas
Mateus Viegas
Arrow right icon
View More author details
Toc

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...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime