Search code examples
entity-frameworkef-fluent-apief-model-builder

Have specific property configuration for all types that implement an interface except for one


I have a number of Types that inherit from the Interface 'IEventReportElement', which exposes the property 'IdEventReport':

public interface IEventReportElement
{
    long Id { get; set; }
    long? IdEventReport { get; set; }
}

This is a nullable property, as I'm not always able to fill it out properly right away, but should be not nullable in the database.

Thats why I have added the line

modelBuilder.Types<IEventReportElement>().Configure(x=>x.Property(y=>y.IdEventReport).IsRequired());

to my OnModelCreating method in the DbContext.

However, the Type 'Position' has to implement this interface, but should NOT have the column for property 'IdEventReport' in the database, but instead a column for the property 'IdParent' it exposes.

public class Position : BOBase, IEventReportElement
{
    public long? IdEventReport 
    {
        get { return IdParent; }
        set { IdParent = value; }
    }

    public long? IdParent { get; set; }
}

and the section in the modelBuilder

        modelBuilder.Entity<Position>().Property(x => x.IdParent).IsRequired();
        modelBuilder.Entity<Position>().Ignore(x => x.IdEventReport);

However, this throws an exception already when trying to Create the database:

System.InvalidOperationException: The property 'IdEventReport' is not a declared property on type 'Position'. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property.

Though this may be valid, is it not possible to override the given Type configuration for a specific type? Do I have to add the line .IsRequired() to every other type that implements this interface, or is there another way to overcome this?


Solution

  • I did find a solution, however it's a not so nice one. I did it by modifying the line of the type configuration to

    modelBuilder.Types<IEventReportElement>().Where(x=>x.Name!="Position").Configure(x=>x.Property(y=>y.IdEventReport).IsRequired());