When using the object initializer syntax, the values specified in the initializer are set after the constructor is executed for the object. If you need values that you want to fill in order to be accessible to the constructor, you must add a constructor form that takes values as arguments and populates fields or properties.
In your class:
public MSReport(int campaignID, DateTime startDate, DateTime endDate) { CampaignID = campaignID; StartDate = startDate; EndDate = endDate;
In your request:
new MSReport(g.Key, d1, d2)
This will work for Linq to SQL and Linq for objects. For Linq to Entities, a different approach should be used.
You can execute the request with an anonymous object, and then run the second request to convert it to the desired object:
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);
Disconnects an object from Linq to Entities and allows you to create the necessary objects using the constructor with parameters. For more information, see the LINQ to Entites "no-parameter constructor" error message in MSDN for more information.
Another option is to execute the request using the MSReport class and object initializer syntax, and then use the Calculate method for your class, which you will need to call later.
source share