如何使用 LINQ to CRM 填充实体只读字段(ModifiedOn、Createdby 等)
本文关键字:ModifiedOn Createdby 读字段 LINQ 何使用 to CRM 实体 填充 | 更新日期: 2023-09-27 18:35:03
我正在尝试运行这个简单的查询:
var appt = (from a in context.AppointmentSet
select new Appointment{ ModifiedOn = a.ModifiedOn}).First();
但是我收到编译器异常,因为 ModifiedOn 是只读的。
- 我可以只返回
a
,但随后将返回Appointment
实体的所有属性,而不仅仅是ModifiedOn
。 - 我可以返回
new { a.ModifiedOn }
,但 appt 将是一个AnonymousType
而不是Appointment
。
建议的方法是什么?
请注意,这是一个示例,假设我从 Appointment 返回的不仅仅是一个属性,然后有一个 where 标准
我总是这样做:
var appt = (from a in context.AppointmentSet
select new Appointment {
Attributes =
{
{ "modifiedon", a.ModifiedOn },
{ "createdon", a.CreatedOn },
{ "createdby", a.CreatedBy }
}
})
.First();
它不需要任何额外的编码,我真的很惊讶没有人在这里发布。
这是我能想到的最有效的方法:
创建一个接受匿名类型(对象(的新构造函数
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;
}
}
}
然后这样称呼它:
var appt = (from a in context.AppointmentSet
select new Appointment(new { a.ModifiedOn })).First();
它必须反映AnoymousType的所有属性,但它应该可以工作,并且具有不必每次都重写属性名称的额外好处。