简体   繁体   English

带有 Ienumerable 的 Asp.net mvc 返回模型

[英]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:我有模型的返回类型 IEnumerable<> 的问题,我试图更好地理解:

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但是,我遇到了编译错误:无法将 Generic.List 类型转换为

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 ?我的问题是:如何才能将 GetAllPhotos() 的 Linq 查询返回为 IEnumerable<> 类型?

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. _ajAentities.Photos似乎是IEnumerable<Models.DB.Photo>类型,但您正试图从您的方法中返回IEnumerable<Photoview>

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.您还可以查看AutoMapper来执行域模型和视图模型之间的映射。

Try this:试试这个:

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

It casts the IQueriable to IEnumerable returned from Linq.它将 IQueriable 转换为从 Linq 返回的 IEnumerable。 Do no use the .ToList() because you're converting it to List type collection.不要使用 .ToList() 因为您要将其转换为 List 类型集合。 Just return the variable.只需返回变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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