Jasper
Jasper

Reputation: 1837

Add data annotations to members in derived class

I've got a solution which is composed out of several projects. One of these projects is a container for POCO objects, shared between all the other projects. Because the objects need to be compatible with Windows Phone, Silverlight, Windows Apps, etc. it's created as a shared library with only a subset of references.

I want to re-use these objects for a code-first implementation of a database model, which requires I add data annotation attributes to the members. But the data annotation namespace is not contained in the reference subset.

So I thought I'd create derived classes in my service API project, to add the data annotations there. But I'm not quite sure how to do this or if it even can be done.

So I'm looking for some ideas, maybe best practices. Of course I could create new models and use a mapping technique to get data from one to the other, but when they're 100% equal that sounds a bit foolish.

Upvotes: 0

Views: 1522

Answers (1)

Richard Deeming
Richard Deeming

Reputation: 31238

Have you tried using the MetadataTypeAttribute?

[MetadataType(typeof(Metadata))]
public class DerivedEntity : PocoEntity
{
   private sealed class Metadata
   {
      [Required, AnotherAnnotation]
      public object NameOfPropertyToDecorate;
   }
}

EDIT
This doesn't work. If you add the MetadataType attribute to the base class, it works; if you add it to the derived class, the annotations are ignored. This behaviour feels like a bug, but there might be a reason for it.

Your best option is probably to use the fluent API to configure your entities.

public class YourContext : DbContext
{
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
      base.OnModelCreating(modelBuilder);
      modelBuilder.Configurations.Add(new PocoEntityConfiguration());
   }
}

public class PocoEntityConfiguration : EntityTypeConfiguration<PocoEntity>
{
   public PocoEntityConfiguration()
   {
      Property(e => e.TheProperty)
         .IsRequired()
         .HasMaxLength(80)
         ...
      ;
   }
}

Upvotes: 2

Related Questions