I'm trying to run this simple query:
var appt = (from a in context.AppointmentSet
select new Appointment{ ModifiedOn = a.ModifiedOn}).First();
but I'm getting a compiler exception since ModifiedOn is readonly.
a
, but then all the attributes of the Appointment
entity will be returned, not just the ModifiedOn
. new { a.ModifiedOn }
, but then appt would be an AnonymousType
and not an Appointment
.What's the suggested way to make this work?
Note, this is an example, assume that I'm returning more than just a single property from Appointment, and then there is a where criteria of some sort
This is the most efficient way I can think of (Edit: This is now a supported option in the Early Bound Generator found in the XrmToolBox):
Create a new constructor that accepts an AnonymousType (Object)
public Appointment(object anonymousType) : this()
{
foreach (var p in anonymousType.GetType().GetProperties())
{
var value = p.GetValue(anonymousType);
if (p.PropertyType == typeof(Guid))
{
// Type is Guid, must be Id
base.Id = (Guid)value;
Attributes["opportunityid"] = base.Id;
}
else if (p.Name == "FormattedValues")
{
// Add Support for FormattedValues
FormattedValues.AddRange((FormattedValueCollection)value);
}
else
{
Attributes[p.Name.ToLower()] = value;
}
}
}
Then call it like so:
var appt = (from a in context.AppointmentSet
select new Appointment(new { a.ModifiedOn })).First();
It has to reflect over all the properties of the AnoymousType, but it should work and has the added benefit of not having to rewrite the properties names each time.