Base solution for your next web application
Open Closed

Calculate NotMapped property when loading from EF #10884


User avatar
0
enio created

Product type: Angular Framework type: .net core ABP Framework version: v11

We do have an entity class defined as below:

[Table("Users", Schema = "Mstr")]
[Audited]
public class User
{
    public virtual string FamilyName { get; set; }

    public virtual string SurName { get; set; }

    [NotMapped]
    public virtual string DisplayName
    {
        get => SurName + " " + FamilyName;
        private set { }
    }
}

This is working just fine. Now we would like to extract the logic part SurName + " " + FamilyName to a helper class which is usually injected with dependency injection. Unfortunately DI is not working for an entity class.

Therefor my question: is there any way in aspnetzero to intercept the creation of new User objects? Is there a method from EF which I could override to execute some additional logic after a User object was created by EF?


6 Answer(s)
  • User Avatar
    0
    musa.demir created

    Hi @enio aspnetboilerplate generates events for CRUD operations of your entities. Can you please check if it meet your needs? https://aspnetboilerplate.com/Pages/Documents/EventBus-Domain-Events#entity-changes

  • User Avatar
    0
    enio created

    Hi @musa.demir

    Thank you for your hint with the entity-changes events. Unfortunately I am looking for an event which is triggered when I query the data and such a predefined event does not exists. EntityCreatingEventData<>-Event is triggered when a new entity is inserted into the database not when a new entity object was created with data from the database.

    Does anyone have another approach?

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    You can also try this approach;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .Property(p => p.DisplayName)
            .HasComputedColumnSql("[SurName ] + '  ' + [FamilyName]");
    }
    
  • User Avatar
    0
    enio created

    Hi @ismcagdas

    Thank you for your hint with the computed column. I already checked out this approach but unfortunately this does not work with Dependency Injection.

    Kind regards, marco

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @enio

    Sorry, I think I couldn't understand your need correctly. Would you like to inject a class to your user entity ? If so, it is not possible. However, you can create a new method in UserManager (or a similar class) and call it right after getting the User from database.

    I can't think of a different approach at the moment.

  • User Avatar
    0
    enio created

    Hi ismagdas

    I see that there is currently no matching hook/event available in entity framework or abp. It seems a bit strange to me that apparently there is no need for that.

    kind regards, marco