0

I have a two table products and categories. When I add a product to products, I get an error. I share the codes.

class Products
{
    public int Id { get; set; }
    public string Name { get; set; }
    public float Price { get; set; }
    public string Description { get; set; }
    public int CategoryId { get; set; }


    public string CategoryName { get; set; }
    public Categories Category { get; set; }
    
}

With this method, I get the products. After I fill a datagridview. But I want to see categoryName instead of CategoryId. It works, I see the categoryName instead of CategoryId in datagridview.

 public List<Products> GetProducts()
    {
        var products = context.Products.Include(x =>x.Category ).Select(m => new Products()
        {
            Id = m.Id,
            Name = m.Name,
            Price = m.Price,
            Description = m.Description,
            CategoryName=m.Category.Name
        }).ToList();

        return products;
    }

After that I have an Add method

  public void AddProduct(Products products )
    {
        context.Products.Add(products);
        context.SaveChanges();
    }

However, when I try to add a new product, I have an error.

error when I try to add a new product

simoncare
  • 75
  • 6

1 Answers1

1

The issue is that Category Name is not in the physical table, just your object. So when EF attempts to generate the SQL, it can't find a column called CategoryName.

Take a look at this question Exclude Property on Update in Entity Framework

Sparky
  • 14,699
  • 1
  • 29
  • 45