簡體   English   中英

實體框架核心無法使用Npgsql獲取Forein關鍵實體

[英]Entity Framework Core getting Forein Key entities not possible with Npgsql

我在實體框架核心的Npgsql的奇怪行為中遇到過:

我的模特:

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數據庫,並且使用“ dotnet ef遷移添加initPG”和“ dotnet ef數據庫更新”創建了架構,而沒有正確的前鍵約束等問題。

然后,我創建一個客戶:

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

與客戶一起提供地址,電子郵件和電話號碼。

我的問題是,當我想從數據庫中獲取所有客戶時:

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

我只有一個空的地址,電子郵件和電話號碼屬性的客戶!!

我在這里有邏輯上的誤解嗎? 我認為EF-Framework會自動將表格加入。 還是我需要手動從客戶那里單獨獲取這些單獨的元素?

在幾個來源中,我看到了include關鍵字來獲取forein-key屬性,但是我的IDE顯示DbContext根本沒有include方法!

如果要include擴展方法,請鍵入

using System.Data.Entity;

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

using Microsoft.EntityFrameworkCore

在文件的頂部

在那時,您應該能夠

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM