【问题标题】:cannot map entities using entity framework core无法使用实体框架核心映射实体
【发布时间】:2021-08-19 09:46:30
【问题描述】:

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

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


    【解决方案1】:

    This 文章可能会有所帮助。

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

    【讨论】:

    • 在哪里添加 Incclode() ?我对实体框架很陌生@John Doe
    • context.Products.Include(p =&gt; p.Supplier),其中context 是 DBContext 类的一个实例。之后,您可以随意过滤您的收藏。
    【解决方案2】:

    你至少需要初始化列表

    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 Supplier() {
          this.Products = new List<Product>();
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-26
      • 2017-06-30
      • 2020-10-15
      • 2020-03-02
      • 1970-01-01
      • 2010-10-09
      • 2017-02-11
      • 2011-03-09
      相关资源
      最近更新 更多