我的问题是,当我有2个查询后,第一个不填充CampaignID属性,而第二个查询.这是我的代码;
查询1;
var query = from c in _context.MCTargets where c.TargetDateFrom==d1 && c.TargetDateTo<=d2 group c by c.MarketingCampaignID into g select new MSReport{ CampaignID = g.Key,// CampaignID is not populated here. StartDate = d1,EndDate = d2 };
查询2;
var query2 = from c in _context.MCTargets where c.TargetDateFrom == d1 && c.TargetDateTo <= d2 group c by c.MarketingCampaignID into g select new { CampaignID = g.Key,StartDate = d1,EndDate = d2 };
MSReport.cs
public class MSReport { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public int CampaignID { get; set; } public MSReport() { // CampaignID = 0 here // doing something with CampaignID here like setting some calculated properties. } }
提前谢谢,抱歉我的解释不好.
解决方法
使用对象初始值设定项语法时,初始化程序中指定的值将在执行对象的构造函数后设置.如果需要将要填充的值用于构造函数,则必须添加构造函数的形式,该值将值作为参数并填充字段或属性本身.
在你的班上:
public MSReport(int campaignID,DateTime startDate,DateTime endDate) { CampaignID = campaignID; StartDate = startDate; EndDate = endDate; // doing something with CampaignID here like setting some calculated properties. }
在您的查询中:
new MSReport(g.Key,d1,d2)
这适用于Linq to sql和Linq to Objects.对于Linq to Entities,必须采取不同的方法.
您可以使用匿名对象执行查询,然后运行第二个查询将其转换为您想要的对象:
var query = from c in _context.MCTargets where c.TargetDateFrom==d1 && c.TargetDateTo<=d2 group c by c.MarketingCampaignID into g select new { CampaignID = g.Key,EndDate = d2 }; IEnumerable<MSReport> queryMSReports = from item in query.AsEnumerable() select new MSReport(item.CampaignID,item.StartDate,item.EndDate);
这会将对象从Linq断开连接到实体,并允许您使用具有参数的构造函数创建所需的对象.有关详细信息,请参阅MSDN上的LINQ to Entites ‘parameterless constructor’ error论坛帖子.
您的另一个选择是使用您的MSReport类和对象初始化程序语法进行查询,然后在您的类上有一个您必须稍后调用的Calculate方法.