Khaled Janky
Khaled Janky

Reputation: 45

cannot map entities using entity framework core

I have in database two tables: product, supplier I want the entity framework to define the supplier of each product I am getting data successfully for two tables but the supplier in the product table is null. Also, the products collection in the supplier table is null. this is my product class:

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

this is the class of supplier:

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

context class:

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

Upvotes: 1

Views: 846

Answers (2)

John Doe
John Doe

Reputation: 203

This article might help.

You should use .Include() to load any related properties.

Upvotes: 2

SirOneOfMany
SirOneOfMany

Reputation: 1084

minimum you need is to initialize the list

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

Upvotes: 0

Related Questions