Chrstpsln
Chrstpsln

Reputation: 777

EF 6 : Nested Complex type in another complex type

Suppose that I have a Entity called "car".

I use a complex type to define the "Engine" part.

[TableName("T_CAR")]
public sealed class Car:IEngine
{
  ...
  public EngineType EngineType{get;set;}

}

[ComplexType]
public sealed class Engine:IEngine
{

  public Engin( )
  {
    this.EnginType = new EngineType( );
  }

  public EngineType EngineType{get;set;}

  // other properties ...

}

[ComplexType]
public sealed class EngineType:IEngineType
{
  ...     
}

When I run this code, I have a error message from EF 6 :

System.InvalidOperationException: The type 'Engine' has already been configured as an entity type. It cannot be reconfigured as a complex type.

And if I remove the definition of EngineType, it works ...

Is there a way to add a nested complex type in another complex type ?

Upvotes: 2

Views: 3020

Answers (2)

phil soady
phil soady

Reputation: 11308

Edit: This has changed, EF6 now supports nested complex types, just remember to set each one as a complex type.

public class EngineConfiguration : ComplexTypeConfiguration<Engine>
{
}
public class EngineTypeConfiguration : ComplexTypeConfiguration<EngineType>
{
}

Then in your context:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new EngineConfiguration());
    modelBuilder.Configurations.Add(new EngineTypeConfiguration());
}

Original answer: No, ComplexTypes may only contain primitive types. I first read this in Julie Lermans book Programming entity framework code first, I don't believe this restriction has been lifted in EF6.

Upvotes: 7

Kuepper
Kuepper

Reputation: 1004

Yes. In my application I got it to work with nested types. But looking at your code I can't spot the error. I used fluent configuration though instead of data attributes.

protected sealed override void OnModelCreating(DbModelBuilder modelBuilder)
  modelBuilder.ComplexType<SampleComplexType>();
}

Upvotes: 3

Related Questions