我做了一個幫助器方法,它會自動將隨機值設置爲給定實體(類)的屬性,這樣我就不必爲每個屬性填充測試時的值。列表<PropertyInfo>除列表<PropertyInfo>不工作
就我而言,每個實體都繼承自BaseEntity類,它具有ID,CreatedBy,CreatedOn等等屬性。基本上這個類具有所有實體共享的所有屬性。
我在這裏想要完成的是將獨特的屬性與常見的屬性分開。
這裏是我的代碼:
public static TEntity PopulateProperties<TEntity>(TEntity entity)
{
try
{
// Since every entity inherits from EntityBase, there is no need to populate properties that are in EntityBase class
// because the Core project populates them.
// First of all, we need to get all the properties of EntityBase
// and then exlude them from the list of properties we will automatically populate
// Get all properties of EntityBase
EntityBase entityBase = new EntityBase();
List<PropertyInfo> entityBaseProperties = new List<PropertyInfo>();
foreach (var property in entityBase.GetType().GetProperties())
{
entityBaseProperties.Add(property);
}
// Get all properties of our entity
List<PropertyInfo> ourEntityProperties = new List<PropertyInfo>();
foreach (var property in entity.GetType().GetProperties())
{
ourEntityProperties.Add(property);
}
// Get only the properties related to our entity
var propertiesToPopulate = ourEntityProperties.Except(entityBaseProperties).ToList();
// Now we can loop throught the properties and set values to each property
foreach (var property in propertiesToPopulate)
{
// Switch statement can't be used in this case, so we will use the if clause
if (property.PropertyType == typeof(string))
{
property.SetValue(entity, "GeneratedString");
}
else if (property.PropertyType == typeof(int))
{
property.SetValue(entity, 1994);
}
}
return entity;
}
finally
{
}
}
的propeblem是var propertiesToPopulate = entityBaseProperties.Except(ourEntityProperties).ToList();
什麼我期待的是,只有唯一這個實體的PropertyInfo對象的列表,但是我從來都是讓我的實體的屬性。 此行不會按預期過濾列表。
任何幫助爲什麼?
如果屬性應該是唯一的_derived_實體類型,不應該它是'propertiesToPopulate = ourEntityProperties.Except(entityBaseProperties)'? –
@RenéVogt我也認爲這種方式應該在理論上起作用。但事實並非如此。 –