Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Models / Entities vs complex types

I have a problem understanding complex data types vs entities in ASP MVC and C#. I started by creating the following type, which is not meant to be an entity (DB table):

public class Period : IPeriod
{
    public DateTime From { get; set; }
    public DateTime To { get; set; }
}

I added this type to a model:

public class Event
{
    public int ID { get; set; }
    public string Title { get; set; }
    public Period EventTime { get; set; }
}

This worked fine. It seemed to understand that Period is a complex type, but not an entity. It just added the columns EventTime_From and EventTime_To to the Event table.

However, then I added some complexity to the Period type by removing the interface, moving the class to a different namespace and adding methods to the class. Suddenly, when trying to rebuild the database, it was suddenly interpreted as an entitytype, thus throwing an Exception for missing a primary key.

What is the system here? When are classes seen as complex types, and when are they seen as entities?

like image 504
Harold Smith Avatar asked Feb 25 '26 23:02

Harold Smith


1 Answers

It is hard to say what exactly is going on without knowing all changes you made but you can always tell EF explicitly that Period is a complex type by either marking it with ComplexType attribute or by using fluent mapping:

modelBuilder.ComplexType<Period>();
like image 142
Ladislav Mrnka Avatar answered Feb 28 '26 14:02

Ladislav Mrnka