Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Extend AbpConcepts in DbContext #2150


User avatar
0
chrisk created

Hi,

I really like idea Abp implementation of certain concepts like IMustHaveTenant. I'm trying to implement something similar. I have created IMustHaveSourceAccount interface and I want to implement logic that will always validate if entity that implements IMustHaveSourceAccount has SourceAccountId property set.

What I got so far is:

protected override void ApplyAbpConcepts() { //Apply our concepts first
ApplyOrdersConnectorConcepts();

        base.ApplyAbpConcepts();
    }

    protected virtual void ApplyOrdersConnectorConcepts()
    {
        var entries = ChangeTracker.Entries().ToList();
        foreach (var entry in entries)
        {
            switch (entry.State)
            {
                case EntityState.Added:
                    CheckMustHaveSourceAccountIdProperty(entry);
                    break;
            }
        }

    }

    protected virtual void CheckMustHaveSourceAccountIdProperty(object entityAsObj)
    {
        if (!(entityAsObj is IMustHaveSourceAccount))
        {
            return;
        }

        var entity = entityAsObj.As<IMustHaveSourceAccount>();
        if (entity.SourceAccountId == 0)
        {
            throw new AbpException("Can not set SourceAccountId to 0 for IMustHaveSourceAccount entities!");
        }
    }

My debugging indicates that there is problem when checking if entity is derived from IMustHaveSourceAccount. I got migrations code with seed data that is inserting few records including entities that derive from IMustHaveSourceAccount and deliberately set SourceAccountId = 0 which should throw exception.

Even when I changed method to throw exception if entity implements my interface nothing happens: protected virtual void CheckMustHaveSourceAccountIdProperty(object entityAsObj) { if (!(entityAsObj is IMustHaveSourceAccount)) { return; } throw new AbpException("Can not set SourceAccountId to 0 for IMustHaveSourceAccount entities!"); }

Throwing exception before If block works so my method is getting called. Do you know what I'm doing wrong?

Thank you


1 Answer(s)
  • User Avatar
    0
    chrisk created

    Hi,

    I found where the problem was, which was very silly btw.

    I was passing EntityEntry object instead of actual entity. CheckMustHaveSourceAccountIdProperty(entry);

    Should be like this CheckMustHaveSourceAccountIdProperty(entry.Entity);