Explicitly map interface member in Entity Framework 7

c# entity-framework entity-framework-core

Question

I'm attempting to map a class which looks like below but I'm getting an exception regarding the Facility.Projects property being an interface.

The property Facility.Projects is of an interface type IProject. If it is a navigation property manually configure the relationship for this property by casting it to a mapped entity type, otherwise ignore the property from the model.

public class Facility : BaseData
{
    [ForeignKey("ClientId")]
    public Client Owner { get; set; }

    public List<IProject> Projects { get; protected set; }

    public Facility()
    {
        Initialize();
    }

    private void Initialize()
    {
        Projects = new List<IProject>();
    }
}

I've mapped other properties via the OnModelCreating method for the DbContext class that Facility is mapped to but I'm not really seeing anything that seems like the right spot to cast this other than HasColumnType which also appears wrong.

public class FacilityRepository : BaseRepository<Facility>, IFacilityRepository
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder
            .Entity<Client>()
            .Property(f => f.Id)
            .ForSqliteHasColumnName("ClientId");

        modelBuilder
            .Entity<Project>()
            .Property(x => x.Id)
            .ForSqliteHasColumnName("ProjectId");


        // area where I've tried and failed to find a good spot to do some manual casting
        modelBuilder
            .Entity<Facility>()
            .Property(f => f.Projects)
            .HasColumnType<Project>(new PropertyBuilder());
    }
}

Can anyone point me in the right direction? I've not seen anything in the documentation that might help? Or should I, by rule, not be doing this at all?

1
2
8/22/2016 8:47:41 PM

Accepted Answer

To do a manual mapping of a one-to-many relationship (this example is just exposing the children on the parent, not vice versa), you can set this up as follows, and then it's pretty straightforward where the cast should be:

        modelBuilder.Entity<ProjectState>()
            .HasMany(h => (ICollection<ProjectRoleState>)h.ProjectRoleStates)
            .WithOne()
            .HasForeignKey(p=>p.ProjectGuid);
3
1/28/2017 10:12:00 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow