【问题标题】:Can not get products from database to list无法从数据库中获取产品列表
【发布时间】:2018-09-30 08:05:50
【问题描述】:

当我想使用将数据从表传输到列表的方法时,我遇到了以下问题。 EntityFramework.dll 中出现“System.Reflection.TargetInvocationException”类型的异常,但未在用户代码中处理

附加信息:调用的目标已抛出异常。 enter image description here

这是我在 phpmyadmin 中的数据库的架构 enter image description here 这是我的 edmx 的架构 enter image description here

Model.cs部分代码

public partial class produkty
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public produkty()
{
    this.zamowienias = new HashSet<zamowienia>();
}

public int idproduktu { get; set; }
public int idtypu { get; set; }
public string nazwa { get; set; }
public byte cena { get; set; }
public string opis { get; set; }
public byte[] image { get; set; }

public virtual typproduktu typproduktu { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<zamowienia> zamowienias { get; set; }
}

public partial class typproduktu
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public typproduktu()
{
    this.produkties = new HashSet<produkty>();
}

public int idtypu { get; set; }
public string nazwa { get; set; }

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<produkty> produkties { get; set; }

当我想使用方法 GetAllProducts 并且我想运行时出现错误时,ProductModel.cs 的这段代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for ProductModel
/// </summary>
public class ProductModel
{
   public string InsertProduct(produkty product)
   {
      try
      {
        komisEntities db = new komisEntities();
        db.produkties.Add(product);
        db.SaveChanges();

        return product.nazwa + " Poprawnie wstawiono";
    }
    catch (Exception e)
    {
        return "Error:" + e;
    }
}

public string UpdateProduct(int idproduktu, produkty product)
{
    try
    {
        komisEntities db = new komisEntities();

        //Fetch object from db
        produkty p = db.produkties.Find(idproduktu);

        p.nazwa = product.nazwa;
        p.idtypu = product.idtypu;
        p.cena = product.cena;
        p.opis = product.opis;
        p.image = product.image;

        db.SaveChanges();
        return product.nazwa + " was succesfully updated";

    }
    catch (Exception e)
    {
        return "Error:" + e;
    }
}

public string DeleteProduct(int idproduktu)
{
    try
    {
        komisEntities db = new komisEntities();
        produkty produkt = db.produkties.Find(idproduktu);

        db.produkties.Attach(produkt);
        db.produkties.Remove(produkt);

        db.SaveChanges();

        return produkt.nazwa + "poprawnie usunięto";
    }
    catch (Exception e)
    {
        return "Error:" + e;
    }
}



public produkty GetProduct(int idproduktu)
{

        using (komisEntities db = new komisEntities())
        {
            produkty product = db.produkties.Find(idproduktu);
            return product;
        }

}





public List<produkty> GetAllProducts()
{
  //  try
 //   {
        using (komisEntities db = new komisEntities())
        {
          List<produkty> products = (from x in db.produkties
            select x).ToList();



            return products;

  }
  //  }
 //   catch (Exception ex)
  //  {
     //   return null;
  //  }

}




public List<produkty> GetProductsByType(int idtypu)
{       
     using (komisEntities db = new komisEntities())
     {
         List<produkty> products = (from x in db.produkties
                                      where x.idtypu == idtypu
                                      select x).ToList();
         return products;

    }

}

}

错误图片: enter image description here

我可以通过这个功能将产品添加到列表以显示数据项和详细信息

       protected void Page_Load(object sender, EventArgs e)
{
    FillPage();

}





private void FillPage()
{
    ProductModel model = new ProductModel();
    List<produkty> products = model.GetAllProducts();

   if (products != null)
 {
  //     Response.Redirect("~/Pages/Login.aspx");
        foreach (produkty product in products)
        {
            Panel productPanel = new Panel();
            ImageButton imageButton = new ImageButton
            {
                ImageUrl = "~/Images/Products/" + product.image,
                CssClass = "productImage",
               PostBackUrl = string.Format("~/Pages/Product.aspx?id={0}", product.idproduktu)
            };
            Label lblName = new Label
            {
              Text = product.nazwa,
                CssClass = "productName"
            };
            Label lblPrice = new Label
            {
                Text = "£ " + product.cena,
                CssClass = "productPrice"
            };

            productPanel.Controls.Add(imageButton);
            productPanel.Controls.Add(new Literal { Text = "<br/>" });
            productPanel.Controls.Add(lblName);
            productPanel.Controls.Add(new Literal { Text = "<br/>" });
            productPanel.Controls.Add(lblPrice);

            //Add dynamic controls to static control
            pnlProducts.Controls.Add(productPanel);
        }
   }
    else
   //    Response.Redirect("~/Pages/About.aspx");
    pnlProducts.Controls.Add(new Literal { Text = "No products found!" });
}

}

但我不能,因为我有消息“未找到产品!”

【问题讨论】:

  • 如果您可以分享以提供更多见解,您内心的例外是什么
  • imgur.com/a/grUwa59@JohnNyingi
  • produkty.cena 在您的模型中是 byte 类型,但在您的数据库中是 decimal(10,0),为什么?

标签: c# mysql asp.net entity-framework


【解决方案1】:

我相信您遇到了数据输入问题:productky.cena 在您的模型中属于 byte 类型,但在您的数据库中属于 decimal(10,0) 类型。我认为这两者之间没有隐式转换,因此屏幕截图中出现“指定的强制转换无效”错误。

【讨论】:

  • 它不起作用。我更改了数据类型,但仍然是同样的问题。 @毛里西奥·莫拉莱斯
  • 遇到同样的错误?你把它改成什么数据类型了? StackOverflow 状态的指导方针我们不能真正帮助您调试代码。绝对听起来可能是打字问题,请检查您的其他映射并确保所有映射都具有隐式转换。这个table 可能会有所帮助。
猜你喜欢
  • 1970-01-01
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2013-01-08
  • 2018-03-31
  • 1970-01-01
相关资源
最近更新 更多