C# 用于从一个类检索集合到另一个类的Linq查询
我有两个类SiteConfig,SiteConfigView。一个与我的EF和一个类紧密耦合,以将其公开给视图模型。这两个类都拥有一组“品牌”类型 我在编写linq查询以从db中获取记录以查看模型时遇到了麻烦 由于我要向视图模型公开一个不同的类,所以必须获取类型为“SiteConfigView”的记录。因此,我正在编写一个linq查询,但我有点困惑如何将集合从SiteConfig获取到SiteConfigView 这是我的课C# 用于从一个类检索集合到另一个类的Linq查询,c#,linq,c#-4.0,entity-framework-4,C#,Linq,C# 4.0,Entity Framework 4,我有两个类SiteConfig,SiteConfigView。一个与我的EF和一个类紧密耦合,以将其公开给视图模型。这两个类都拥有一组“品牌”类型 我在编写linq查询以从db中获取记录以查看模型时遇到了麻烦 由于我要向视图模型公开一个不同的类,所以必须获取类型为“SiteConfigView”的记录。因此,我正在编写一个linq查询,但我有点困惑如何将集合从SiteConfig获取到SiteConfigView 这是我的课 public partial class SiteConfig {
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; }
}
public部分类SiteConfig
{
公共站点配置()
{
this.SiteBrands=new HashSet();
}
public int IdSiteConfig{get;set;}
公共字符串名称{get;set;}
公共字节[]SiteLogo{get;set;}
公共字符串{get;set;}
公共字符串LinkColor{get;set;}
公共虚拟ICollection站点{get;set;}
}
公共类SiteConfigView
{
公共站点配置视图()
{
}
public int IdSiteConfig{get;set;}
公共字符串名称{get;set;}
公共字节[]SiteLogo{get;set;}
公共字符串{get;set;}
公共字符串LinkColor{get;set;}
公共IEnumerable站点品牌{get;set;}
}
这就是我正在尝试的问题
var db = new SampleMVCEntities();
IQueryable<SiteConfig> test = db.SiteConfigs.Select(a => new SiteConfigView{Name = a.Name,LinkColour = a.LinkColour,SiteLogo = a.SiteLogo});
var db=new SampleMVCEntities();
IQueryable test=db.SiteConfigs.Select(a=>newsiteconfigview{Name=a.Name,linkcolor=a.linkcolor,SiteLogo=a.SiteLogo});
comebody可以指导我如何将集合从SiteConfig获取到SiteConfigView
谢谢你正朝着正确的方向努力
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();
谢谢你的回复。但是上面的查询不包括集合SiteBrand。请检查我的更新答案,很抱歉,您需要给出
SiteBrandView
模型的定义,以帮助您执行ProjectionTanks John。在SiteConfigs上调用Select之前是否需要调用AsEnumerable。调用AsEnumerable
接口的原因是,您从DBcontext接收的元素集合是可读取的,并且要进行投影(在您的情况下转换为另一个类,即视图模型)
你需要实现的是这个接口。我不明白你的观点,实现这个接口是可行的。我可以调用。直接在SiteConfigs上选择而不调用。AsEnumarable()。无论如何,这两件事我都要试试。如果你能解释一下两者的区别,那就太好了。谢谢