实体框架核心使用Npgsql无法获得Forein Key实体

时间:2016-07-26 20:44:36

标签: c# entity-framework postgresql npgsql .net-core

我遇到了Npgsql for Entity Framework Core的奇怪行为:

我的模特:

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; }
}

我的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);
    }
}

我已成功连接到postgresql数据库,并使用&#34; dotnet创建架构ef迁移添加initPG&#34;和#34; dotnet ef数据库更新&#34;没有问题与右外围关键约束等等。

然后我创建了一个客户:

var created = _context.Customers.Add(cust);
_context.SaveChanges();

客户包含地址,电子邮件和电话号码。

我的问题是当我想从DB获取所有客户时:

IEnumerable<Customer> customers = _context.Customers.ToList();

我只有一个拥有空地址,电子邮件和电话号码属性的客户!!

我在这里有误解吗??我认为EF-Framework会自动连接表。 或者我手动需要自己从客户那里获得这些单独的元素吗?

在多个来源,我看到 include 关键字来获取forein-key属性,但我的IDE显示DbContext根本没有 include 方法!

1 个答案:

答案 0 :(得分:2)

如果您需要include扩展方法,请输入

using System.Data.Entity;

或者,如果按照rubiktubik的建议使用EF 7

using Microsoft.EntityFrameworkCore

位于文件顶部

那时候,你应该可以做到

IEnumerable<Customer> customers = _context.Customers
    .Include(c => c.Emails)
    .ToList();