Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

winforms - WindowsForms-EFCore SQL Exception Invalid Column Name

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

question from:https://stackoverflow.com/questions/65890429/windowsforms-efcore-sql-exception-invalid-column-name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...