Friday, October 19, 2012

Check value exists in entity frame work.

Let’s say you want to check the existence of a particular value in the database table. For example I have a view named RoomTypeEntityView in edmx file as follows. I want to check a given RoomTypeName is exists or not. There are so many approaches to do this in entity framework.

One way to check the exsistence is get the result as ToList() and get the Count. This approach is little bit low performance. This need to check every row and to get the count.
Another easiest way is using Any() method. This will not check every row in the table. This will return true once it finds a match.

Example code:

public bool IsRoomTypeAlreadyExists(int accomodationId, string roomTypeName)
            bool status = false;

            using (TripBagEntities entities = DataObjectFactory.CreateContext())
                status = entities.RoomTypeEntityViews.Where(c => c.AccommodationId == accomodationId && c.RoomTypeName == roomTypeName).Any();

                return status;

No comments:

Post a Comment