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:
- 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; }
}
}
- 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?
BranchId
property in newBranch
class?Company.Id
,Branch.Id
, and so on. If you need to maintain uniqueness, use unique constraints at database level,Add-Migration
?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.