好的,我会提出一个新的答案(有点晚了,抱歉),即使协会的名称发生变化,它也会起作用。
此方法将查找主实体的关联属性,然后在主表中查找值。设想:
表:通过equalsOrders
引用表。所以我们传递了主表的Meta信息,字段(也就是被引用的字段)和字段(就是我们想要的值)。Customers
Orders.CustomerID
Customers.Id
CustomerID
Name
/// <summary>
/// Gets the value of "referencedValueFieldName" of an associated table of the "fieldName" in the "mainTable".
/// This is equivalent of doing the next LINQ query:
/// var qryForeignValue =
/// from mt in modelContext.mainTable
/// join at in modelContext.associatedTable
/// on mt.fieldName equals at.associatedField
/// select new { Value = at.referencedValueField }
/// </summary>
/// <param name="mainTable">Metadata of the table of the fieldName's field</param>
/// <param name="fieldName">Name of the field of the foreign key</param>
/// <param name="referencedValueFieldName">Which field of the foreign table do you the value want</param>
/// <returns>The value of the referenced table</returns>
/// <remarks>This method only works with foreign keys of one field.</remarks>
private Object GetForeignValue(MetaTable mainTable, string fieldName, string referencedValueFieldName) {
Object resultValue = null;
foreach (MetaDataMember member in mainTable.RowType.DataMembers) {
if ((member.IsAssociation) && (member.Association.IsForeignKey)) {
if (member.Association.ThisKey[0].Name == fieldName) {
Type associationType = fPointOfSaleData.GetType();
PropertyInfo associationInfo = associationType.GetProperty(member.Name);
if (associationInfo == null)
throw new Exception("Association property not found on member");
Object associationValue = associationType.InvokeMember(associationInfo.Name, BindingFlags.GetProperty, null, fPointOfSaleData, null);
if (associationValue != null) {
Type foreignType = associationValue.GetType();
PropertyInfo foreignInfo = foreignType.GetProperty(referencedValueFieldName);
if (foreignInfo == null)
throw new Exception("Foreign property not found on assiciation member");
resultValue = foreignType.InvokeMember(foreignInfo.Name, BindingFlags.GetProperty, null, associationValue, null);
}
break;
}
}
}
return resultValue;
}
和电话:
AttributeMappingSource mapping = new System.Data.Linq.Mapping.AttributeMappingSource();
MetaModel model = mapping.GetModel(typeof(WhateverClassesDataContext));
MetaTable table = model.GetTable(typeof(Order));
Object value = GetForeignValue(table, "CustomerId" /* In the main table */, "Name" /* In the master table */);
问题是它只适用于只有一个引用字段的外键。但是,更改为多个键非常简单。
这是一种获取主表字段值的方法,可以改成返回整个对象。
PS:我觉得我的英语有一些错误,这对我来说是相当困难的。