0

Here's part of the setup. Names are simplified: I have following classes:

  • MyClass
  • MySubclass1 : MyClass
  • MySubClass2 : MyClass

MyClass is part of another class (and table), which I will leave out.

I'm trying to do an EF6 query (using context.Set<MyClass>.Where(...))

I want to return the subclasses instead of the parent class and I want to avoid using the Discriminator. The reason is: there is a property on MyClass that already defines whether it's MySubclass1 or MySubclass2. The property is called KindId and is an FK to a lookup table (Kinds).

The EF-part is being autogenerated as follows:

public partial class MyClassMap : EntityTypeConfiguration<MyClass>
{
    public MyClassMap ()
    {
        ToTable("MyClasses", "MySchema");
        //...etc (other implementations)

        HasRequired(c=> c.Kind)
            .WithMany(kind => kind.MyClasses)
            .HasForeignKey(c => new { c.KindId });

        Initialize();
    }

    partial void Initialize();
}

This means, I can only update Initialize(). I have done so as follows:

public partial class MyClassMap 
{
    partial void Initialize()
    {
        Map<MySubclass1>(c => c.Requires("KindId").HasValue(1));
        Map<MySubclass2>(c => c.Requires("KindId").HasValue(2));
    }
}

When I run the EF query, I'm getting following exception:

error 3023: Problem in mapping fragments starting at lines x:Column MyClass.KindId has no default value and is not nullable. A column value is required to store entity data.

I tried setting the default value on the DB, but I think it requires the Default to be set within EF. Question is: how do I do this using the FluentApi?

Recipe
  • 1,398
  • 3
  • 16
  • 29

1 Answers1

0

You're probably getting an error because it doesn't know what discriminator value to use for the base class. So, I think you also need a map for the base class -- for example:

Map<MyClass>(c => c.Requires("KindId").HasValue(0));
jjj
  • 4,822
  • 1
  • 16
  • 39
  • Thanks for your answer. It's quite a good suggestion. Unfortunately, it changes the exception to following: 'The type MyClass has already been mapped to table 'MySchema.MyClasses'. Specify all mapping aspects of a table in a single Map call.' I do know that it is mapped, just not in the current map. Any suggestions? – Recipe Jun 05 '15 at 20:09
  • Ah, yea, the `Map` also needs to include `c.ToTable("MyClasses", "MySchema")`...but if you can't modify the generated configuration.... – jjj Jun 05 '15 at 20:52
  • You are correct, the .ToTable is unfortunately generated :( – Recipe Jun 05 '15 at 21:17
  • @Recipe: what are you using for the code generation? – jjj Jun 05 '15 at 22:21
  • It's a domain modeling tool (custom written by framework guys) that translates (together with T4-templates) to c# – Recipe Jun 06 '15 at 09:55