[英]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.