MVC finding row in database not using primary key

c# entity-framework linq

Question

Assuming I have the following class:


public class Item

{
     [Key]
     public int itemID {get; set;}
     public int typeID {get; set;}
}

I understand that finding a record in database usually is by the primary key, e.g.

Item item = db.Item.Find(id);

How do I find the record by another column? i.e. find all the records where typeID = 1?

1
4
2/25/2013 5:30:32 PM

Accepted Answer

Item item = db.Items.FirstOrDefault(i => i.typeID == 1);

Keep in mind, that if you are not using primary key, then there could be more than one item matching your query. You can use FirstOrDefault as in sample above to get first (if any) item which matches query.

To get all items with specified type id, use Where:

var items = db.Items.Where(i => i.typeID == 1);
6
2/25/2013 5:29:35 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow