【问题标题】:WindowsForms-EFCore SQL Exception Invalid Column NameWindows 窗体-EF Core SQLException 列名无效
【发布时间】:2021-04-29 14:13:16
【问题描述】:

我有两个表产品和类别。当我将产品添加到产品时,我收到错误消息。我分享代码。

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

通过这种方法,我得到了产品。在我填写一个datagridview之后。但我想查看 categoryName 而不是 CategoryId。它有效,我在 datagridview 中看到的是 categoryName 而不是 CategoryId。

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

之后我有一个 Add 方法

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

但是,当我尝试添加新产品时,出现错误。

【问题讨论】:

    标签: sql winforms entity-framework-core


    【解决方案1】:

    问题是类别名称不在物理表中,只是您的对象。因此,当 EF 尝试生成 SQL 时,它找不到名为 CategoryName 的列。

    看看这个问题 Exclude Property on Update in Entity Framework

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      相关资源
      最近更新 更多