Error generating linq data list

1

Launches the following error:

  

The entity or complex type 'SisVentaOnlinne.Models.Card' can not be constructed in LINQ to Entities query.

This is the method that the list with the data generates:

    public List<Card> GetCard()
    {
        var user = db.Usuarios.Where(u => u.Email == User.Identity.Name).FirstOrDefault();
        var card = (from Cards in db.Cards.Where(u => u.Id_Usuario == user.Id_Usuario)
                    select new Card
                    {
                        CardNumber = Cards.CardNumber.Replace((Cards.CardNumber.Substring(1 - 1, 12)), "************"),
                        IdCard = Cards.IdCard,
                    }).ToList();

        return card.ToList();
    }
    
asked by Ing. Jose Valera 24.04.2018 в 14:08
source

1 answer

1

The problem is that you try to build a model from an entity and the worst could come when you leave the transaction open to the View because you send a db.Cars .

The ideal is to use a model so that you have the interaction with the view and also make a dispose of the transaction.

Class of the model (Data Transfer Object):

public class CardsModel
{
    public string CardNumber { get; set; }
    public string IdCard { get; set; }
}

Controller Code:

public List<Card> GetCard()
{
    List<CardsModel> cards = new List<CardsModel>();

    using(db = new DataContext()){
        var user = db.Usuarios.Where(u => u.Email == User.Identity.Name).FirstOrDefault();
        cards = (from Cards in db.Cards
                where Cards.Id_Usuario == user.Id_Usuario
                select new CardsModel
                {
                    CardNumber = Cards.CardNumber.Replace((Cards.CardNumber.Substring(1 - 1, 12)), "************"),
                    IdCard = Cards.IdCard,
                }).ToList();
    }
    return card.ToList();
}
    
answered by 24.04.2018 / 16:35
source