Cem*_*Cem 8 c# entity-framework linq-to-sql c#-4.0
我的问题是,当我有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
};
Run Code Online (Sandbox Code Playgroud)
查询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
};
Run Code Online (Sandbox Code Playgroud)
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.
}
}
Run Code Online (Sandbox Code Playgroud)
提前谢谢,抱歉我的解释不好.
Jam*_*See 16
使用对象初始值设定项语法时,初始化程序中指定的值将在执行对象的构造函数后设置.如果需要将要填充的值用于构造函数,则必须添加构造函数的形式,该值将值作为参数并填充字段或属性本身.
在你的班上:
public MSReport(int campaignID, DateTime startDate, DateTime endDate)
{
CampaignID = campaignID;
StartDate = startDate;
EndDate = endDate;
// doing something with CampaignID here like setting some calculated properties.
}
Run Code Online (Sandbox Code Playgroud)
在您的查询中:
new MSReport(g.Key, d1, d2)
Run Code Online (Sandbox Code Playgroud)
这适用于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,
StartDate = d1,
EndDate = d2
};
IEnumerable<MSReport> queryMSReports = from item in query.AsEnumerable()
select new MSReport(item.CampaignID, item.StartDate, item.EndDate);
Run Code Online (Sandbox Code Playgroud)
这会将对象从Linq断开连接到实体,并允许您使用具有参数的构造函数创建所需的对象.有关详细信息,请参阅MSDN上的LINQ to Entites'无参数构造函数'错误论坛帖子.
您的另一个选择是使用您的MSReport类和对象初始化程序语法进行查询,然后在您的类上有一个您必须稍后调用的Calculate方法.
也许默认构造函数在参数初始化之前运行?尝试使用您的参数在 MSReport 中添加构造函数并进行调试。
public class MSReport
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int CampaignID { get; set; }
public MSReport(int campaginId, ....)
{
// use and initialize camaginId here
}
}
Run Code Online (Sandbox Code Playgroud)
并做:
select new MSReport(g.Key) {
StartDate = d1,
EndDate = d2
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51588 次 |
| 最近记录: |