无法隐式转换类型。存在显式转换(您是否错过了演员?)

时间:2014-06-29 20:20:04

标签: c# asp.net .net generics

我正在尝试使用ASP.Net Web API开发Web应用程序。现在在创建Product model和IProductRepository接口后,我很难显示所有产品。我收到错误消息

  

无法将System.Collections.Generic.IEnumerable<WebApplication1.Models.Product>类型隐式转换为System.Collections.Generic.IEnumerable<WebApplication1.Product>。存在显式转换(您是否错过了演员?)

     

Controllers \ ProductsController.cs 17 20 WebApplication1

在这行代码上

return repo.GetAll();

我不明白该怎么做。如果有人指出问题并向我解释我做错了什么会非常有帮助。

ProductsController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class ProductsController : ApiController
    {
        static readonly IProductRepository repo = new ProductRepository();

        public IEnumerable<Product> GetAllProducts()
        {
            return repo.GetAll();
        }
    }
}

ProductRepository.cs

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

namespace WebApplication1.Models
{
    public class ProductRepository : IProductRepository
    {
        public string cs = System.Configuration.ConfigurationManager.ConnectionStrings["MediaSoftAppEntities"].ConnectionString;

        public IEnumerable<Product> GetAll()
        {
            List<Product> products = new List<Product>();
            string sql = String.Format("Select [ProductID], [ProductName], [Price] FROM [Products]");

            using (SqlConnection con = new SqlConnection(cs)){
                using (SqlCommand cmd = new SqlCommand(sql, con)){
                    con.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    while(dr.Read()){
                        Product product = new Product();
                        product.ProductID = dr.GetInt32(0);
                        product.ProductName = dr.GetString(1);
                        product.Price = dr.GetInt32(2);
                    }
                }
            }
            return products.ToArray();
        }
    }
}

IProductRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public interface IProductRepository
    {
        IEnumerable<Product> GetAll();
    }
}

1 个答案:

答案 0 :(得分:2)

错误是说编译器认为是 ProductsController.GetAllProducts想要返回WebApplication1.Product 但是IProductRepository.GetAll会返回WebApplication1.Models.Product

这2个不同的命名空间中是否有2个Product类?

或者,也许你以前在Product命名空间中有WebApplication1类,它现在已被移动到WebApplication1.Models命名空间中,也许你只是有一个陈旧的引用和一个&#34;重建所有&#34;将解决它。