【发布时间】:2018-03-29 14:12:50
【问题描述】:
我正在研究将在我们的实体中动态创建集合实例的方法。我的问题是,当我创建必须插入数据库的新记录时,我的 ICollection 导航属性始终为空并且在我的安全方法中
我必须使用下面这样的东西来创建新的List,这绝对不是好方法。如果我不创建List 的实例,Mapper 将抛出错误,它无法将某些东西的Collection 映射到null,例如它无法将Categories 的列表映射到null。
我的安全方法示例
//check if record exists in database so i know if have to update or insert record (based on entity Id)
var entity = repository.GetById(detail.Id)
//....some code removed for brevity
if (entity.Categories == null)
{
entity.Categories = new List<Category>();
}
if (entity.UserContacts == null)
{
entity.UserContacts = new List<UserContact>();
}
//dto => entity
Mapper.PopulateEntity(dto, entity);
//update or insert later on.
必须创建List<T> 实例的扩展方法,例如new List<Category>(),如上所示。
public TEntity InitializeEntity(TEntity entity)
{
var properties = entity.GetType().GetProperties();
foreach (var prop in properties)
{
if (typeof(ICollection<TEntity>).Name == (prop.PropertyType.Name))
{
var get = prop.GetGetMethod();
//get assembly with entity namespace and class name
var fullName = get.GetBaseDefinition().ReturnType.GenericTypeArguments[0].AssemblyQualifiedName;
//create instance of object
var myObj = Activator.CreateInstance(Type.GetType(fullName));
//check if property is null or if get some value, dont want to rewrite values from database
var value = prop.GetValue(entity);
if (value == null)
{
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(myObj.GetType());
Activator.CreateInstance(constructedListType);
}
}
}
return entity;
}
由于某种原因,它根本没有创建任何实例,我无法弄清楚问题出在哪里。
【问题讨论】:
标签: c# list reflection instance