2

I am currently migrating EF Core 3.0 code-first entity to clean architecture approach.

In EF Core 3.0 this works fine:

namespace SmartCom.Models
{
    public class branch
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [MaxLength(128)]
        public virtual string CompanyId { get; set; }

        [MaxLength(128)]
        public string AddressId { get; set; }

        public DateTime CreatedDate { get; set; }

        public int RefNo { get; set; }

        [ForeignKey("AddressId")]
        public address Address { get; set; }
    }
}

At the DB context

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<branch>()
  .HasKey(c => new { c.CompanyId, c.BranchId });

With clean architecture, I separated entity business logic from persistence as follows:

  1. Business logic model without persistence settings;
namespace SmartComCA.CoSec.Domain.Entities
{
    public class Branch
    {
        public virtual Company Company { get; set; }
        public Address Address { get; set; }
        public DateTime CreatedDate { get; set; }
        public int RefNo { get; set; }
    }
}
  1. Persistence configuration in Infrastructure project:
namespace SmartComCA.CoSec.Infrastructure.Persistence.Configuration
{
    public class BranchConfiguration : IEntityTypeConfiguration<Branch>
    {
        public void Configure(EntityTypeBuilder<Branch> builder)
        {
            //builder.HasKey(t => new { t.Company, t.Address});

            builder.HasOne(t => t.Company).WithMany()
                .HasForeignKey("CompanyId");

            builder.HasOne(t => t.Address).WithMany()
                .HasForeignKey("AddressId");

            builder.ToTable("branch");
        }
    }
}

This compiles but fails during add-migration. How do I specify composite foreign key as primary key in clean architecture where persistence is abstracted from business logic?

10
  • Do you really want address to be a part of primary key? Also, where is BranchId property in new Branch class?
    – Dennis
    Dec 8, 2020 at 8:23
  • Yes, a company has many branches and each branch has a unique address.
    – Sh Hue Nga
    Dec 8, 2020 at 8:27
  • 3
    Don't do that. This brings unnecessary complexity to your database. If some entity have to refer the branch, that entity table will need to keep all of branch PK fields inside as a foreign key fields. It's better to keep PKs as simple as possible - just use Company.Id, Branch.Id, and so on. If you need to maintain uniqueness, use unique constraints at database level,
    – Dennis
    Dec 8, 2020 at 8:32
  • Can you include the error message from Add-Migration? Dec 8, 2020 at 8:41
  • 1
    @ShHueNga in any case the phrase clean architecture contains no useful information for this particular question. Yes, you can create composite keys. No, you probably shouldn't use them. UNLESS you use EF Core 5 and have a many-to-many table, in which case EF Core 5 maps them transparently. Dec 8, 2020 at 9:51

1 Answer 1

2

You can replace the explicit properties with shadow properties. Which you already did indirectly with HasForeignKey fluent API, but following is the explicit definition matching the original definition which also correctly configures the max length for string data types:

builder.Property<string>("CompanyId")
    .IsRequired()
    .HasMaxLength(128);

builder.Property<string>("BranchId")
    .IsRequired()
    .HasMaxLength(128);

Then you can define the composite PK using the shadow property names:

builder.HasKey("CompanyId", "BranchId");

But please note that having shadow PK imposes some limitations/requirements for operations like update and delete, since they would require having the loaded related objects rather than just their keys.

6
  • Using a composite key for a M:N table will create problems if one of the keys has to change. EF Core may not know whether the new combination is a new record or a modified one Dec 8, 2020 at 9:53
  • I'm starting to fear the phrase clean architecture approach Dec 8, 2020 at 9:56
  • @PanagiotisKanavos In EF Core keys of any sort (primary/alternate, simple/composite) are not mutable. It doesn't matter if they are mapped to "real" or shadow properties. The choice of using composite keys with that limitation is up to you. I don't think our goal is to analyze people's design - in this case, they already have that composite key in their original design, so this (un fact EF Core) is just giving them an option to do the same with shadow properties.
    – Ivan Stoev
    Dec 8, 2020 at 9:57
  • I had web apps in mind, where edits come as detached entities. The key protection can't help there Dec 8, 2020 at 10:00
  • @PanagiotisKanavos Actually I don't care about architectural terms. My goal is to provide EF Core data model mapping for their "doman" or whatever they call them models when possible. If I have to share opinion, they should really use separate models - one which follows "their" concepts/rules, and one for persistence. And map between the two where needed.
    – Ivan Stoev
    Dec 8, 2020 at 10:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.