7

When using OwnsOne to map complex types, the sql column name is prefixed with the attribute name. Is it possible to specify the prefix name in the mapping?

This is my mapping:

e.OwnsOne(x => x.Attributes, cb =>
{
    cb.OwnsOne(a => a.Supplier);
});

I would like the sql column to be prefixed with "Attr_" Instead of "Attributes_". Is this possible?

4
  • 1
    Currently this convention is hardcoded. You may post a feature request to github.com/aspnet/EntityFrameworkCore/issues. The workaround is to configure explicitly column names for all properties (including those of the nested owned type).
    – Ivan Stoev
    Commented Jan 10, 2018 at 20:07
  • @Ivan Stoev, Do you know the syntax to map explicity. Just tried in a IEntityTypeConfiguration file: builder.Property(x=>x.Address.Postcode).HasColumnName("PostCode"). but it throws an Exception ArgumentException: The expression 'ea => ea.Address.Postcode' is not a valid property expression. The expression should represent a property access: 't => t.MyProperty'. Parameter name: propertyAccessExpression
    – Jafin
    Commented Feb 27, 2018 at 7:29
  • 8
    @Jafin It has to be done through the corresponding OwnsOne builder action argument. e.g. .OwnsOne(e => e.Address, cb => { cb.Property(e => e.Postcode).HasColumnName("Postcode"); });
    – Ivan Stoev
    Commented Feb 27, 2018 at 7:45
  • You can also use data annotations to override column names. e.g. annotating with [Column("Supplier")] will use that for column name without prefix. The attribute Column exists in the namespace System.ComponentModel.DataAnnotations.Schema This method has the advantage of being local to the entity class file so other developers adding additional properties can notice the need to override column names by noting existing properties.
    – Mohammad
    Commented Feb 26, 2019 at 11:14

2 Answers 2

5

You could write an extension method to override the names of all columns;

   public static void WithPrefix<T, R>(this OwnedNavigationBuilder<T, R> builder, string prefix) where T:class where R:class
   {
      foreach (var p in builder.OwnedEntityType.GetProperties())
         p.SetColumnName($"{prefix}{p.Name}");
   }

   .OwnsOne(e => e.Address, cb => cb.WithPrefix(""));
2

Ivan Stoev's answer from the question comments:

It has to be done through the corresponding OwnsOne builder action argument. e.g. .OwnsOne(e => e.Address, cb => { cb.Property(e => e.Postcode).HasColumnName("Postcode"); });

(Making this a community wiki, just marking the question as being answered.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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