'EF Core - How to create a relation when the foreign key is a concatenated field with constant value
I have to map in Entity Framework a database with weird relations. There is no primary key nor foreign key, I guess relations by analysing already existing SQl request. And there is a case I cannot define in fluent api.
The SQL request
SELECT *
FROM TABLE_A A
INNER JOIN TABLE_B B ON A.Company = B.Company AND A.Kind = 7 AND A.[Key] = CONCAT(B.Field1, B.Field2, '000', B.Field3)
I expect a one to one relationship, so I tried somethink like that in the context:
modelBuilder.Entity<Table_A>(A =>
A.HasOne(x => x.Table_B).WithOne(x => x.Table_A)
.HasForeignKey<Table_B>(x => new { x.Company, x.Kind, x.Key })
.HasPrincipalKey<Table_A>(x => new { Company = x.Company, Kind = 7, Key = $"{x.Field1}{x.Field2}000{x.Field3}" });
);
I got an error that told I must use direct property acces in the HasPrincipalKey object construction.
I also tried to create a read only property in the Table_A class like that:
Public virtual string Key => $"{Field1}{Field2}000{Field3}";
and I adapt the context (I remove the Kind property because of the constant)
modelBuilder.Entity<Table_A>(A =>
A.HasOne(x => x.Table_B).WithOne(x => x.Table_A)
.HasForeignKey<Table_B>(x => new { x.Company x.Key })
.HasPrincipalKey<Table_A>(x => new { x.Company, x.Key });
);
in that case I have a message about a missing setter on the property Key. I also tried various stuff but without any success.
If anyone knows how to translate this SQL relation into EF Core fluent API, I would be glad to hear it. Thank you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
