views:

29

answers:

1

Hi all

Here is the question : I have following entities: alt text

Every time i update or insert a transaction i would like to autodetect the category depending on ReferenceMappingExpression or DescriptionMapppingExpression in CategoryMappings Entity. I mean i want to match Transaction.Description to CategoryMappings.DescriptionMapping and if it matches get the FkCategoryID from CategoryMapping and save the transactions. It is possible to loop throug every transaction in list and categorymapping list but i dont think its good idea. How would you do this? Any suggestions? Any experience of that?

+1  A: 

You can use ObjectStateManager, add a partial OnContextCreated method to your entity context. Add new handler to SavingChanges event of context. Get all added and modified transactions there and do whatever you want inside it. Like this:

public partial class ModelContainer
{
    partial void OnContextCreated()
    {
        this.SavingChanges += new EventHandler(ModelContainer_SavingChanges);
    }

    void ModelContainer_SavingChanges(object sender, EventArgs e)
    {
        foreach (var item in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added))
        {
            SetTransactionDescription(item);
        }
        foreach (var item in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified))
        {
            SetTransactionDescription(item);
        }
    }

    void SetTransactionDescription(System.Data.Objects.ObjectStateEntry entry)
    {
        Transaction transaction = entry.Entity as Transaction;
        if (transaction != null)
        {
            // Your code
        }
    }
}
Musa Hafalır