简体   繁体   中英

Linq query to retrieve collection from one class to another class

I have 2 classes SiteConfig, SiteConfigView. One is tightly coupled with my EF and one class to expose it to View models. Both the classes holds to a collection of type 'Brands'

I struck at writing a linq query to fetch the records from db to view model.

As I am exposing a different class to view model, I have to get the records of type 'SiteConfigView'. So I am writing a linq query but I am bit confused how to get the collection from SiteConfig to SiteConfigView.

There are my classes

public partial class SiteConfig
{
    public SiteConfig()
    {
        this.SiteBrands = new HashSet<SiteBrand>();
    }

    public int IdSiteConfig { get; set; }
    public string Name { get; set; }
    public byte[] SiteLogo { get; set; }
    public string Brands { get; set; }
    public string LinkColour { get; set; }

    public virtual ICollection<SiteBrand> SiteBrands { get; set; }
}

public class SiteConfigView
{
    public SiteConfigView()
    {

    }

    public int IdSiteConfig { get; set; }
    public string Name { get; set; }
    public byte[] SiteLogo { get; set; }
    public string Brands { get; set; }
    public string LinkColour { get; set; }

    public IEnumerable<SiteBrandView> SiteBrands { get; set; }
}

And this is the query I am trying

var db = new SampleMVCEntities();
        IQueryable<SiteConfig> test = db.SiteConfigs.Select(a => new SiteConfigView{Name = a.Name,LinkColour = a.LinkColour,SiteLogo = a.SiteLogo});

Can comebody guide me how to get the collection from SiteConfig to SiteConfigView.

Thanks

You're going on the right direction tried like this

var siteConfigs = db.SiteConfigs.AsEnumerable().Select(a => new SiteConfigView()
                 {
                     Name = a.Name,
                     LinkColour = a.LinkColour,
                     SiteLogo = a.SiteLogo,
                     SiteBrands = a.SiteBrands.AsEnumerable().Select(a => new SiteBrandView()
                     {
                          //Do the projection
                     }).ToList()
                 }).ToList();

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