我有以下方法,期望string[] include
参数包含实体的动态子集:
public virtual CEntity GetByID(int id,string[] include = null)
{
// for testing
include = new string[] { "TypeEntity" };
using (var _context = new CodeGenerator.Data.AppContext())
{
TEntity dbEntity = default;
if (include != null)
{
var query = _context.Set<TEntity>().AsnoTracking();
//problem here >
for (int i = 0; i < include.Length; i++)
{
query.Include(include[i]);
}
// debugging the sql statement > it didn't add any include statements,just selec statement
// expected dbEntity.TypeEntity != null
// actual result dbEntity.TypeEntity = null
dbEntity = query.Where(e => e.ID == id).FirstOrDefault();
}
else
{
dbEntity = _context.Set<TEntity>().AsnoTracking().FirstOrDefault(e => e.ID == id);
}
if (dbEntity == null)
{
return null;
}
return _mapper.Map<CEntity>(dbEntity);
}
}
我的实体ProjectEntityProperty
public interface IEntity
{
int ID { get; set; }
}
public class Entity : IEntity
{
public int ID { get; set; }
}
public class ProjectEntityProperty : Entity
{
public int EntityId { get; set; }
public string Name { get; set; }
public string Type { get; set; } = "string";
public int? TypeEntityId { get; set; }
public int Order { get; set; } = 0;
public bool Isnullable { get; set; } = false;
public bool IsPrimary { get; set; } = false;
public ProjectEntity TypeEntity { get; set; }
public ProjectEntity Entity { get; set; }
}
include语句不包含项目的子集TypeEntity
,但是此代码有效:
return _context.ProjectEntityProperties.AsnoTracking()
.Include("TypeEntity")
.Where(k => k.EntityId == entityId)
.ToList()
.Select(_mapper.Map<ProjectEntityProperty>)
.ToList();
我的函数GetByID
出问题了吗?