Home > other >  How to combine several entities into one in entity framework (map complex entity into single table)
How to combine several entities into one in entity framework (map complex entity into single table)

Time:10-22

Just for example. I have two models

public class Person {
    public int Id { get; set: }
    public string Name { get; set; }
    public Birth Date { get; set; }
}
public class Birth {
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
}

How to make the entity framework seeing the 'Person' entity like this:

public class Person {
    public int Id { get; set: }
    public string Name { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
}

i.e. EF should map it into single table.

CodePudding user response:

If you are using EF Core this can be achieved with so called "Owned Entities". Using atrributes:

public class Person 
{
    public int Id { get; set: }
    public string Name { get; set; }
    public Birth Date { get; set; }
}

[Owned]
public class Birth 
{
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
}

Or explicit configuration:

modelBuilder.Entity<Person>().OwnsOne(p => p.Date);

Note that Birth fields will be prefixed.

  • Related