Data Annotations Complex Type Attribute in Entity Framework

The complex type attribute denotes the class as a complex type. The complex type is a class, which is similar to an entity, but with few differences.

What is Complex Type

Consider the entity model class below. Here the ContactInfo is a Complex Type, which is shared by both Customer and Employee entity. All you need to do is to decorate the class with ComplexType Attribute. This attribute resides in the  System.ComponentModel.DataAnnotations.Schema

  • Complex types do not have primary keys, hence they do not exist independently.
  • They can exist as the properties of other entities or other complex types
  • We cannot define foreign key relationships on complex types

Complex Type Attribute

When you add the ComplexType Attribute the EF does not generate the table for the class. But it creates the columns in each and every entity which refers to the Complex Type as shown in the image below. It creates the Column with the name as <PropertyName>_<ComplexTypePropertyName>

Data Annotations Complex Type Attribute in Entity Framework
Data Annotations Complex Type Attribute in Entity Framework Code First

Best Entity Framework Core Books

Best Entity Framework Books

References

  1. ComplexTypeAttribute

1 thought on “Data Annotations Complex Type Attribute in Entity Framework”

  1. no funciona con .net core 3.1
    The entity type ‘ContactInfo’ requires a primary key to be defined. If you intended to use a keyless entity type call ‘HasNoKey()’

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top