【发布时间】:2019-12-02 15:40:51
【问题描述】:
假设我有以下实体
public abstract class BaseEntity {
public Guid Id { get;set; }
public string Prop1 { get;set; }
public long Prop2 { get;set; }
public byte Type_Id { get;set; }
}
public class Type1 : BaseEntity { }
public class Type2 : BaseEntity { }
public class Type3 : BaseEntity {
public long? Prop3 { get;set; }
}
以及以下上下文映射:
builder.ToTable("Entities").HasDiscriminator(a => a.Type_Id)
.HasValue<Type1>((byte)Types.Type1)
.HasValue<Type2>((byte)Types.Type2)
.HasValue<Type3>((byte)Types.Type3);
// in DbContext
public DbSet<BaseEntity> Entities { get; set; }
我想从 DB(所有记录)中创建 get IQueryable Type1 和 Type2 在 Prop3 中将具有 null , 我执行以下操作:
public DbSet<BaseEntity> DBSet { get;set; }
private static readonly MethodInfo FromSqlMethodInfo = typeof(RelationalQueryableExtensions).GetTypeInfo().GetDeclaredMethods("FromSql").Single(mi => mi.GetParameters().Length == 3);
public IQueryable<Type3> GetEntities(IEnumerable<Guid> ids) {
RawSqlString sql = @"select [Id]
,[Prop1]
,[Prop2]
,[Prop3]
,[Type_Id]
from [dbo].[Entities] where Id in (select item from @Ids)";
var ids = new SqlParameter("@Ids", SqlDbType.Structured);
ids.TypeName = typeof(Guid).Name.ToLowerInvariant() + "_item_list";
ids.Direction = ParameterDirection.Input;
ids.Value = CreateItemList(tpIds);
var param = new object[] { ids };
var conversion = from s in DBSet select (Type3)s;
var result = conversion.Provider.CreateQuery<Type3>(Expression.Call(null, FromSqlMethodInfo.MakeGenericMethod(typeof(Type3)), conversion.Expression,
Expression.Constant(sql), Expression.Constant(param)));
return result;
}
var query = GetEntities(someIds);
var result = query.OrderBy(m => m.Type_Id).Skip(skip).Take(take).ToList();
并且查询执行成功,但是调用ToLIst时,抛出异常: 无法将“Type1”类型的对象转换为“Type3”类型,这是意料之中的,因为我们没有告诉它应该如何转换……所以问题是:EF Core 可以做到这样的技巧吗?
【问题讨论】:
标签: c# .net entity-framework implicit-conversion ef-core-2.2