Convert IEnumerable frow WCF to another local IEnumerable is that possible? .net c# casting dapper model-view-controller

Question

I have this function in a WCF service:

public IEnumerable<Product> ListProducts()
{
    return dal.RunDapper<Product>("listarProdutos");
}

It will execute a proc with Dapper and map data with this class:

[DataContract]
public class Product
{
    [DataMember]
    public int PRODUCTID { get; set; }
    [DataMember]
    public string PRODUCTNAME { get; set; }
    [DataMember]
    public string COMPANYNAME { get; set; }
    [DataMember]
    public string CATEGORYNAME { get; set; }
    [DataMember]
    public decimal UNITPRICE { get; set; }
    [DataMember]
    public int UNITINSTOCK { get; set; }
}

In my Local Model:

public IEnumerable<Product> ListarProdutos()
{
    var retorno = WCF.ListProducts();
    return retorno.Cast<Product>();
}

and my local Product class has same properties:

public class Product
{
    public int PRODUCTID { get; set; }
    public string PRODUCTNAME { get; set; }
    public string COMPANYNAME { get; set; }
    public string CATEGORYNAME { get; set; }
    public decimal UNITPRICE { get; set; }
    public int UNITINSTOCK { get; set; }
}

This is my controller:

public ActionResult Index()
{
    ProductDB produtos = new ProductDB();
    var model = produtos.ListProducts();

    return View(model);
}

My View model:

<tr>
    <td>@Html.DisplayNameFor(model => model.PRODUCTNAME)</td>
    <td class="hidden-xs">@Html.DisplayNameFor(model => model.COMPANYNAME)</td>
    <td>@Html.DisplayNameFor(model => model.CATEGORYNAME)</td>
    <td class="hidden-xs">@Html.DisplayNameFor(model => model.UNITPRICE)</td>
    <td>@Html.DisplayNameFor(model => model.UNITINSTOCK)</td>
</tr>

I am getting this error:

Unable to cast object of type ModeloTemplate.NorthWindWCF.Product to type ModeloTemplate.Models.Product.

Popular Answer

The WCF service reference created a type for Product as ModeloTemplate.NorthWindWCF.Product. You defined a type (as you said, locally) as ModeloTemplate.Models.Product. These are two different, unrelated types and cannot be cast back and forth automatically. Check out AutoMapper.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why