DEV Community

Birol AYDIN
Birol AYDIN

Posted on

Using Entity Framework Core 8 Owned Types HasData()

  • First, let's write two sample classes
public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; } = null!;
    public string LastName { get; set;} = null!;

    public Contact PersonalInformation { get; set; } = null!;
}
Enter fullscreen mode Exit fullscreen mode
using Microsoft.EntityFrameworkCore;

[Owned]
public class Contact
{
    public string PhoneNumber { get; set; } = null!;
    public string EmailAddress { get; set; } = null!;
}
Enter fullscreen mode Exit fullscreen mode
  • Let's create the Person Table with the help of DbContext class and Entity Framework Core.
public sealed class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : DbContext(options)
{
    public DbSet<Person> People => Set<Person>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Person>(p =>
        {
            p.HasData(
                new Person
                {
                    Id = 1,
                    FirstName = "Person 1",
                    LastName = "Surname 1"
                },
                new Person
                {
                    Id = 2,
                    FirstName = "Person 2",
                    LastName = "Surname 2"
                },
                new Person
                {
                    Id = 3,
                    FirstName = "Person 3",
                    LastName = "Surname 3"
                });

            p.OwnsOne(e => e.PersonalInformation).HasData(new
            {
                PersonId = 1,
                EmailAddress = "EmailAddress 1",
                PhoneNumber = "1111111111111111"
            },
            new
            {
                PersonId = 2,
                EmailAddress = "EmailAddress 2",
                PhoneNumber = "22222222222222"
            },
            new
            {
                PersonId = 3,
                EmailAddress = "EmailAddress 3",
                PhoneNumber = "3333333333333333"
            });
        });
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Now it's time to create the database with the entity framework migration command and then update the database.
Add-Migration Initial
Enter fullscreen mode Exit fullscreen mode
Update-Database
Enter fullscreen mode Exit fullscreen mode

that is all . enjoy your work 😊

Top comments (0)