Technology Lover
Technology Lover

Reputation: 259

How to use Enum to get the number of records based on the selected type?

I am using Linq-To-Entities and I am trying to use Enum for retrieving the number (count) of items based on the status. For instance, the status of item could be active or inactive or pending. What I did in my Business Logic Layer is the following:

public enum ItemStatus   
    {
        Active = 1,
        Inactive = 2,
        Pending = 3
    }

public int getActiveItemsCount()
    {
        using (ItemsDBEntities context = new ItemsDBEntities())
        {
            return context.Items.Count();
        }
    }

Here's is my database schema:

Items Table: ID, Name, StatusID
Status Table: ID, Status

As you see, there is a relationship between Items and Status tables.

What I want is to modify the second method in such a way that will the number of items based on the status of the item. Could you please tell me how to create a method similar to the second one for getting the number of items based on the status listed by Enum?

Upvotes: 0

Views: 242

Answers (1)

James World
James World

Reputation: 29796

Assuming the StatusID matches your Enum, then like this on EF 4 (which has no native Enum support):

public int getActiveItemsCount(ItemStatus status)
{
    using (ItemsDBEntities context = new ItemsDBEntities())
    {
        var enumvalue=(int)status;
        return context.Items.Where(item => item.StatusID == enumvalue).Count();
    }
}

Upvotes: 3

Related Questions