简体   繁体   中英

Asp.net mvc return model with Ienumerable

I am having a problem of the return type IEnumerable<> of the model which I try to better understand:

I am having a Model view:

public class Photoview
{
    public int IdPhoto { get; set; }
    public DateTime Date { get; set; }
    public string Nom { get; set; }
    public int Category { get; set; }
    public string Lien { get; set; }
    public bool Actif { get; set; }
    public string Description { get; set; }
}

and a model, which gets data from the database:

    public IEnumerable<Photoview> GetAllPhotos()
    {
        var a = from o in _ajAentities.Photos
                select o;

        return a.ToList();
    }

However, I am having a compile error :cannot convert type Generic.List to

The table of the database is:

id_photo    int         Unchecked
date    smalldatetime   Checked
nom         nvarchar(250)   Checked
categorie   int         Checked
lien    nvarchar(250)   Checked
actif   bit         Checked
description nvarchar(800)   Checked

My question is: How would I make it possible to return the Linq query of GetAllPhotos() as IEnumerable<> type ?

Thanks

It seems that the _ajAentities.Photos is of type IEnumerable<Models.DB.Photo> and yet you are trying to return an IEnumerable<Photoview> from your method.

So the first possibility is to fix your return type to match that of your database entity:

public IEnumerable<Photo> GetAllPhotos()
{
    var a = 
        from o in _ajAentities.Photos
        select o;
    return a.ToList();
}

The second possibility is to map between the two types:

public IEnumerable<Photoview> GetAllPhotos()
{
    var a = 
        from o in _ajAentities.Photos
        select new Photoview
        {
            IdPhoto = o.Id,
            Date = o.Date,
            Nom = o.Nom,
            ....
        };

    return a.ToList();
}

You might also take a look at AutoMapper to perform the mapping between your domain models and your view models.

Try this:

var a = (IEnumerable<Object>)
        from o in _ajAentities.Photos
        select o;

It casts the IQueriable to IEnumerable returned from Linq. Do no use the .ToList() because you're converting it to List type collection. Just return the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM