Optimization Required.

Posts   
 
    
Prem Singh
User
Posts: 7
Joined: 21-Jun-2011
# Posted on: 29-Aug-2011 13:25:16   

Can you please help me to optimize this code and write in a single filter.


public static bool DeleteFriends(Guid memberGUID, Guid friendGUID)
        {
            bool success = false;

            DataAccessAdapter adapter = new DataAccessAdapter();
            EntityCollection<FriendEntity> friendEntity = new EntityCollection<FriendEntity>();

            RelationPredicateBucket bucket = new RelationPredicateBucket();
            bucket.PredicateExpression.Add(FriendFields.MemberGuid == memberGUID);
            bucket.PredicateExpression.AddWithAnd(FriendFields.FriendGuid == friendGUID);

            adapter.FetchEntityCollection(friendEntity, bucket);
            adapter.CloseConnection();

            if (friendEntity.Count > 0)
            {
                adapter.OpenConnection();
                adapter.DeleteEntityCollection(friendEntity);
                adapter.CloseConnection();
                success = true;
            }
            else
            {
                EntityCollection<FriendEntity> friendEntity1 = new EntityCollection<FriendEntity>();

                RelationPredicateBucket bucket1 = new RelationPredicateBucket();
                bucket1.PredicateExpression.Add(FriendFields.FriendGuid == memberGUID);
                bucket1.PredicateExpression.AddWithAnd(FriendFields.MemberGuid == friendGUID);

                adapter.OpenConnection();
                adapter.FetchEntityCollection(friendEntity1, bucket1);
                adapter.CloseConnection();

                if (friendEntity1.Count > 0)
                {
                    adapter.OpenConnection();
                    adapter.DeleteEntityCollection(friendEntity1);
                    adapter.CloseConnection();
                    success = true;
                }
            }
            return success;
        }

Thanks in advance.

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 29-Aug-2011 16:06:15   

You did not explain what are you trying to do, or what's the target SQL.

As far as I undertand from the code, you want to delete a friend relationship between 2 members. So you have 2 GUIDs and you want to delete any records in a Friend table that associate these GUIDs with each other.

All you have to do is to implement the following SQL:

DELETE FROM Friend
WHERE 
(MemberGuid = memberGUID AND FriendGuid == friendGUID)
OR
(MemberGuid = friendGUID AND FriendGuid == memberGUID)

I'll leave the rest for you.

Hints: - You don't need to fetch anything to execute the delete command. - You don't need to open and close connections, these are done automatically. - The connection can be kept open to execute multiple commands, this can be done by passing true to the DataAccessAdapter Ctor.