4

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
  • 1
    Note that this has almost nothing to do with MVC itself - it's purely a function of your model and data access layer, which is generally agnostic toward the hosting application. Commented Feb 25, 2013 at 17:21

1 Answer 1

6
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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.