C#C
C#4y ago
Stroniax

EF Core SQL Generation with Custom Type [Answered]

I've got a custom type
AssetId
, which is an AK member of the type
Asset
.
class Asset {
  int Id; // PK
  AssetId? AssetId; // AK
}
struct AssetId {
  private int _value;
  static AssetId Parse(string s);
  string ToString();
}
class AssetIdConverter : ValueConverter<AssetId, string> {
  AssetIdConverter(): base(e => e.ToString(), e => AssetId.Parse(e), new ConverterMappingHints(size: 8, unicode: false) {}
}

// inside DbContext.ConfigureConventions
builder.DefaultTypeMapping<AssetId>().HasConversion<AssetIdConverter>().IsUnicode(false).HasMaxLength(8).IsFixedLength();
builder.Property<AssetId>().HasConversion<AssetIdConverter>().IsUnicode(false).HasMaxLength(8).IsFixedLength();

The
AssetId
type is internally an
int
, but for a number of reasons including the fact that it logically contains two values, it is stored as
char(8)
in the db.

No matter how I configure this type, it seems querying against it in EF is always generating SQL like the following:
CONVERT(Asset.AssetId as NVARCHAR(max)) = N'00-00-00'
(where 00-00-00 is an
AssetId.ToString()
). I do not want to convert the value to
NVARCHAR(max)
for this. It shouldn't have to change from
char(8)
at all.
Was this page helpful?