So I have a pair of related objects that are being tied through a secondary key that don’t have the same type and I am trying to relate the objects together. In essence I have something like.
public class A
{
Guid PK {get;set;}
string ReferenceKey {get;set;} // is an internal and external key so generically typed
ICollection<B> RelatedClassBObjs {get;set;} // this can be null
}
public class B
{
int Key {get;set}
A RelatedClassAObj {get;set;}
}
Class A’s ReferenceKey is sometimes a reference to Class B’s Key and so is an int, but in other times it can be an external reference and so could be anything from a GUID to a random string.
I’m attempting to relate the 2 classes using Fluent API doing something like
modelBuilder.Entity<B>(entity=>{
... //Property set up omitted
entity.HasOne(e => e.RelatedClassAObj)
.WithMany(d=>d.RelatedClassBObjs)
.HasForeignKey(e=>e.Key)
.HasPrincipalKey(d => d.ReferenceKey);
});
and I have the alternate key set up for Class A as well
modelBuilder.Entity<A>(entity=>{
entity.HasKey(e => e.PK)
.HasName("PRIMARY");
entity.HasAlternateKey(e => e.ReferenceKey )
.HasName("reference_key");
... // extra setup omitted
});
With this setup the join SQL generated looks like
JOIN B b ON b.Key = a.ReferenceKey
However this seems to be attempting to cast/read the string ReferenceKey as an integer and then blows up when there is a non-integer present. In the SQL this seems to be able to be fixed by adding a cast to string around the b.Key
JOIN B b ON CAST(b.Key as string) = a.ReferenceKey
But I cannot figure out a way to get fluent API to do this. I have no control over the Data bases, nor over the Linq queries (the model is being used by HotChocolate so I do not have direct Linq/SQL control). Any help would be greatly appreciated.