首页 > 解决方案 > 无法使用实体框架核心映射实体

问题描述

我在数据库中有两个表:产品,供应商我希望实体框架定义每个产品的供应商我成功获取两个表的数据,但产品表中的供应商为空。此外,供应商表中的产品集合为空。这是我的产品类别:

public class Product 
{       
   public int  id { get; set; }           
   [Column("Productname", TypeName = "ntext")]
   public string Name { get; set; }           
   public decimal UnitPrice { get; set; }
   public bool isDiscounted { get; set; }
   public int quantity { get; set; }            
   public int SupplierId { get; set; }
   [ForeignKey("SupplierId")]
   public  Supplier supplier { get; set; }            
}

这是供应商的类别:

public class Supplier
{           
   public int Id { get; set; }
   public string CompanyName { get; set; }
   public string ContactName { get; set; }
   public string  ContactTitle { get; set; }
   public string city { get; set; }
   public string country { get; set; }
   public string phone { get; set; }
   public string Fax { get; set; }
   public List<Product> Products { get; set; }    
 }

上下文类:

 public class DbConext : DbContext
 {
    public DbSet<Product> Products { get; set; }
    public DbSet<Supplier> Suppliers { get; set; }
    public DbConext(DbContextOptions<DbConext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>().ToTable("Product");
        modelBuilder.Entity<Supplier>().ToTable("Supplier");
        modelBuilder.Entity<Product>().HasKey("id");
        modelBuilder.Entity<Supplier>().HasKey("Id");
        modelBuilder.Entity<Product>().HasOne(p => p.supplier).WithMany(s => s.Products).HasForeignKey(p => p.SupplierId);                  
    }
 }

标签: c#entity-framework-core

解决方案


这篇文章可能会有所帮助。

您应该使用.Include()加载任何相关属性。


推荐阅读