MVC search for a row in a database that does not use a primary key

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 a database is usually done using a primary key, for example.

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

How to find an entry in another column? i.e. find all records where typeID = 1 ?

+4
source share
1 answer
 Item item = db.Items.FirstOrDefault(i => i.typeID == 1); 

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

To get all elements with the specified type identifier, use Where :

 var items = db.Items.Where(i => i.typeID == 1); 
+6
source

All Articles