我做了一个帮助器方法,它会自动将随机值设置为给定实体(类)的属性,这样我就不必为每个属性填充测试时的值。列表<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我也认为这种方式应该在理论上起作用。但事实并非如此。 –