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.
Table of Contents
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
1 2 3 4 5 6 7 8 9 10 11 12 | public class Customer { public Customer() { Contact = new ContactInfo(); } public int CustomerID { get; set; } public string Name { get; set; } public ContactInfo Contact { get; set; } } |
1 2 3 4 5 6 7 8 9 10 11 12 | public class Employee { public Employee() { EmployeeContact = new ContactInfo(); } public int EmployeeID { get; set; } public string Name { get; set; } public ContactInfo EmployeeContact { get; set; } } |
1 2 3 4 5 6 7 8 | [ComplexType] public class ContactInfo { public string Email { get; set; } public string Phone { get; set; } } |
- 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>
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()’
This tutorial is for ADO.NET.
If you are using ASP.NET the attribure you are looking for is called
Owned
.Reference: https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities