I have encountered in a strange behavior of Npgsql for Entity Framework Core:
My Models:
public class Customer
{
public Customer()
{
Numbers = new List<TelephoneNumber>();
Emails = new List<Email>();
}
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string SecondName { get; set; }
public Address Address { get; set; }
public List<TelephoneNumber> Numbers {get;set;}
public List<Email> Emails { get; set; }
public string Note { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public string Street { get; set; }
public int HouseNumber { get; set; }
public int Code { get; set; }
public string City { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
public class Email
{
public int EmailId { get; set; }
public string Address { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
public class TelephoneNumber
{
public int TelephoneNumberId { get; set; }
public string Number { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
And my DbContext:
public class CustomerContext : DbContext
{
public CustomerContext(DbContextOptions<CustomerContext> options) : base(options)
{}
public DbSet<Customer> Customers {get; set;}
public DbSet<Address> Addresses { get; set; }
public DbSet<Email> Emails {get;set;}
public DbSet<TelephoneNumber> Numbers {get;set;}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Customer>().HasKey(m => m.CustomerId);
builder.Entity<Address>().HasKey(m => m.AddressId);
builder.Entity<Email>().HasKey(m => m.EmailId);
builder.Entity<TelephoneNumber>().HasKey(m => m.TelephoneNumberId);
base.OnModelCreating(builder);
}
}
I have successfully connected to the postgresql database and the schema is created with "dotnet ef migrations add initPG" and "dotnet ef database update" without problems with right forein key constrains-etc..
Then i create a customer with:
var created = _context.Customers.Add(cust);
_context.SaveChanges();
With customer containing a address,email and telephone number.
My problem is when i want to get all customers from the DB with:
IEnumerable<Customer> customers = _context.Customers.ToList();
I only get a Customers with empty Address, Email and TelephoneNumber properties!!
Do i have a logical misunderstanding here!? I would think the EF-Framework does the table joins automatically. Or do i manually need to get this seperate elements from the customer by myself?
At several sources i see the include keyword to get the forein-key properties but my IDE shows that the DbContext has no include method at all!