Generic deletes using adapter mode

Posts   
 
    
rboarman
User
Posts: 83
Joined: 01-Feb-2005
# Posted on: 13-Mar-2012 00:58:38   

Hello,

I am using version 3.1 Final dated 2/22/2012 in adapter mode.

Based on this response by daelmo, I am trying to get his example code to work to allow me to delete multiple entities based on a key in a generic manner.

http://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=17841

My code:

public void Delete<T>(object key) where T : class, new()
        {
            var entity = new T();

            // get pk
            var pkField = (EntityField2)((IEntity2)entity).GetPrimaryKey();

            // create filter
            var filter = new PredicateExpression();
            filter.Add(pkField == key);

            // fetch
            var coll = ((IEntity2)entity).GetEntityFactory().CreateEntityCollection();
            coll.GetMulti(pkField == key);

            this.Adapter.DeleteEntityCollection(coll);

            return; 
        }

        public static IEntityField2 GetPrimaryKey(this IEntity2 entity)
        {
            return entity.PrimaryKeyFields[0];
        }

The issue is that GetMulti is not part of IEntityCollection2. How do I fill the collection and then delete the entities? Is there an easier way?

Thank you.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 13-Mar-2012 06:25:21   

Hi there,

For adapter is slightly different, because the persistence logic in adapter is outside the entity. Also you don't need to fetch the entity, you can direct call DeleteEntitiesDirectly. Try this:

public void Delete<T>(object key) where T : IEntity2, new()
{
    var entity = new T();

    // get pk
    var pkField = (EntityField2) GetPrimaryKey((IEntity2)entity);

    // create filter
    var filter = new RelationPredicateBucket();
    filter.PredicateExpression.Add(pkField == key);

    using (var adapter = new DataAccessAdapter())
    {
        adapter.DeleteEntitiesDirectly(typeof(T), filter);
    }

    return;
}

public static EntityField2 GetPrimaryKey(IEntity2 entity)
{
    return (EntityField2) entity.PrimaryKeyFields[0];
}

Usage:

Delete<CustomerEntity>("ALFI");

Note that this code only works if the entity has just 1 PK field. If the entity has a composite key, then you will delete multiple rows, not just one.

David Elizondo | LLBLGen Support Team
rboarman
User
Posts: 83
Joined: 01-Feb-2005
# Posted on: 13-Mar-2012 17:57:20   

Worked perfectly. Thank you!