【发布时间】:2017-03-02 00:34:58
【问题描述】:
我正在创建一个辅助方法,它会自动为给定实体(类)的属性设置随机值,这样我就不必在测试时为每个属性填充值。
在我的例子中,每个实体都继承自 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
{
}
}
问题在于var propertiesToPopulate = entityBaseProperties.Except(ourEntityProperties).ToList();
我期待的是一个仅对该实体唯一的 PropertyInfo 对象列表,但是我总是得到我的实体的所有属性。 此行未按预期过滤列表。
有什么帮助吗??
【问题讨论】:
-
如果属性对于派生实体类型应该是唯一的,不应该是
propertiesToPopulate = ourEntityProperties.Except(entityBaseProperties)吗? -
@RenéVogt 我也认为这种方法理论上应该可行。但事实并非如此。
标签: c# entity-framework