0

I am involved in a project where we map already existing C# code to database using Entity Framework Code First. I am not going to reproduce the code itself here, but I will present some pseudo-code that should cover the same issue.

I am trying to map a class to the database that has lists of other classes. I will show you an example:

public Class ListClass 
{
    public List<SubClassA> ListOne
    {
        get { return BaseClass.OfType<SubClassA>().Where(b => !b.BoolOne && b.BoolTwo).ToList(); }
    }

public List<SubClassA> ListTwo
    {
        get { return BaseClass.OfType<SubClassA>().Where(b => b.BoolOne && b.BoolTwo).ToList(); }
    }
}


public abstract class BaseClass
{
    public bool BoolOne {get; set;}

    #Region EF
    public GUID PrimaryKey {get; set;}
    public GUID ListClassForeignKey {get; set;}
    #EndRegion
}

public class SubClassA : BaseClass
{
    public bool BoolTwo {get; set}
}

Class SubClassB : BaseClass
{
    //Contents..
}

Summary: ListClass contains lists of SubClassA. The BaseClass and SubClassA does not know anything about the ListClass. The GUID-attributes in BaseClass is added for use with Entity Framework, otherwise no existing classes have been changed. That is why we use Fluent API for this project:

class ListClassConfiguration : EntityTypeConfiguration<ListClass>
{
    public ListClassConfiguration()
    {
        HasKey(f => f.PrimaryKey);
        Property(f => f.PrimaryKey).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasMany(f => f.ListOne).WithOptional().HasForeignKey(f => f.ListClassForeignKey);
        HasMany(f => f.ListTwo).WithOptional().HasForeignKey(f => f.ListClassForeignKey);

    }
}

In the Context-class we simply add this configuration. The database is deleted whenever the model is changed. I am currently using TPH-mapping for the BaseClass and it's sub-classes.

When I try to add and save the ListClass with the refered objects in the list, I get this exception:

InvalidOperationException. The foreign key component 'ListClassForeignKey' is not a declared property on type 'SubClassA'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.

So, any advice?

Edit: I've noticed that in the real project, there seem to be empty lists. I tried to remove the foreignkey in the configuration-class, and I got a databasetable with no contents (one row with only NULL-values in the columns). In this example, that would mean that the TPH-table with the name 'BaseClass' only is empty / has only NULL-values. Could that explain some of the problem?

Darth_Sygnious
  • 528
  • 3
  • 7
  • 18

1 Answers1

0

Never mind, a collegue pointet out a problem with the list-properties: Only getters, no setters, and they are based on a list of the BaseClass that's also used by the ListClass

Darth_Sygnious
  • 528
  • 3
  • 7
  • 18