abp icon indicating copy to clipboard operation
abp copied to clipboard

Recommended way to extend entities and configure foreign keys

Open duard-sf opened this issue 6 years ago • 4 comments

The documentation has been useful to explain how to extend ABP modules' entities using ObjectExtensionManager.

However, it does not provide an explanation on how to extend an entity with a foreign key. I would like to request elaboration on how that would be done in the latest (as of writing, 2.7) version of ABP.

Example: I have an entity called RoleTest, which should have a one-to-many relationship with ABP's IdentityRole. I.e., IdentityRole should get a RoleTestId foreign key property.

EfCoreEntityExtensionMappings

ObjectExtensionManager.Instance
    .MapEfCoreProperty<IdentityRole, int?>(
        "RoleTestId"
    );

DbContext

builder.Entity<IdentityRole>(b =>
{
    b
        .HasOne<RoleTest>()
        .WithMany()
        .HasForeignKey("RoleTestId");
});

I am aware that configuration done in the EntityFrameworkCore project's DbContext is only relevant during runtime. We used to have a ModelBuilder extension method for ConfigureCustomUserProperties, or something like that, which was called from the DbMigrations project, if I'm not mistaken.

Now, it seems that pattern of configuring existing entities has been removed, possibly replaced with something else, but I am not aware of the proper way to do this.

duard-sf avatar May 15 '20 07:05 duard-sf

@hikalkan Any progress? I met the same problem.

PMExtra avatar Oct 02 '20 15:10 PMExtra

To demonstrate it, I have created a demo project with MVC UI & EF Core. The solution name is ForeignDemo.

Department Entity

I created a Department entity:

public class Department : AggregateRoot<int>
{
    public string Name { get; set; }
}

A User will have a department and a department can be many users (1 to many relation)

I added a DbSet property to ForeignDemoDbContext

public DbSet<Department> Departments { get; set; }

and defined the mapping in the ForeignDemoDbContextModelCreatingExtensions:

builder.Entity<Department>(b =>
{
    b.ToTable("AppDepartments");
    b.ConfigureByConvention();
    b.Property(x => x.Name).IsRequired();
});

There is nothing special so far.

Configuring the Extension Property

In the ForeignDemoModuleExtensionConfigurator.ConfigureExtraProperties method, I added the following code:

ObjectExtensionManager.Instance.Modules()
    .ConfigureIdentity(identity =>
    {
        identity.ConfigureUser(user =>
        {
            user.AddOrUpdateProperty<int?>(
                "DepartmentId"
            );
        });
    });

This makes the ABP framework know the extra property.

In the ForeignDemoEfCoreEntityExtensionMappings.Configure method, I added the following code:

ObjectExtensionManager.Instance
    .MapEfCoreProperty<IdentityUser, int?>("DepartmentId");

This tells EF Core migrations to add DepartmentId field to the users table.

Configuring the Foreign Key

This the essential point. I add the following code to ForeignDemoMigrationsDbContext.OnModelCreating method, just before the builder.ConfigureForeignDemo(); line:

builder.Entity<IdentityUser>(b =>
{
    b.HasOne(typeof(Department))
        .WithMany()
        .HasForeignKey("DepartmentId");
});

That's all. When I create a new migration, I see the relation:

// Departments table

migrationBuilder.CreateTable(
    name: "AppDepartments",
    columns: table => new
    {
        Id = table.Column<int>(nullable: false)
            .Annotation("SqlServer:Identity", "1, 1"),
        ExtraProperties = table.Column<string>(nullable: true),
        ConcurrencyStamp = table.Column<string>(maxLength: 40, nullable: true),
        Name = table.Column<string>(nullable: false)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_AppDepartments", x => x.Id);
    });

// Foreign Key to the AbpUsers table

migrationBuilder.AddColumn<int>(
    name: "DepartmentId",
    table: "AbpUsers",
    nullable: true);

migrationBuilder.CreateIndex(
    name: "IX_AbpUsers_DepartmentId",
    table: "AbpUsers",
    column: "DepartmentId");

migrationBuilder.AddForeignKey(
    name: "FK_AbpUsers_AppDepartments_DepartmentId",
    table: "AbpUsers",
    column: "DepartmentId",
    principalTable: "AppDepartments",
    principalColumn: "Id",
    onDelete: ReferentialAction.Restrict);

The key point is that: Why I added foreign key definition to ForeignDemoMigrationsDbContext.OnModelCreating. Because, this is the only place that it only appears in the migrations. If I do it in the ForeignDemoEfCoreEntityExtensionMappings, then the IdentityDbContext (which indirectly calls this method) will include the Department entity to its model. But we don't want to do it.

The UI part

DepartmentId will be available on the UI (table and create/edit forms). On the table:

image

You can remove it from the UI easily. If you want to show the department name instead, you need to work more, however it is not today's topic.

hikalkan avatar Oct 22 '20 10:10 hikalkan

@hikalkan Is it possible to use this for one-to-one relationships? I followed the exact steps with exception to the OnModelCreating method where I put WithOne() instead of WithMany() and I ended up with error saying:

You are configuring a relationship between 'IdentityUser' and 'Employee' but have specified a foreign key on 'EmployeeId'. The foreign key must be defined on a type that is part of the relationship.

UPDATE: I figured it out. I had to call HasForeignKey with primary table and property names. builder.Entity<IdentityUser>(b => { b.HasOne(typeof(Employee)).WithOne().HasForeignKey("IdentityUser","EmployeeId"); });

dkaczor97 avatar Sep 29 '21 14:09 dkaczor97

@hikalkan I tried to extend issue mentioned above.I want to send user with department name from my api .When trying to join user with Department entity by using linq ,my linq query is not converted succesfully.Can we use extra properties like this?Is It possible?

public async Task<IdentityUserDto> GetAsync(Guid id)     
 {
           var result= from identityUser in userRepository.GetQueryableAsync()
                          join department in await _departmentRepository.GetQueryableAsync() on identityUser.GetDepartmentId() 
                          equals  department.Id
			  where identityUser.Id == id
                          select new { identityUser, department};                          
          
            var userDto = ObjectMapper.Map<IdentityUser, IdentityUserDto>(result.identityUser);
            userDto.SetProperty("DepartmentName",result.department.Name);
            
            return userDto;
}

My extension method like below

public static Guid GetDepartmentId(this IdentityUser user)
{
           return user.GetProperty<Guid>("DepartmentId");
}

And I extend IdentityUserDto

 ObjectExtensionManager.Instance
      .AddOrUpdateProperty<IdentityUserDto, string>("DepartmentName");

ZerinKvl avatar Jan 11 '22 11:01 ZerinKvl