[英]Cast int to enum from sql query C# Entity Framework
如何使用NewUnitPhaseStatus
作为枚举返回IEnumerable
?
在SQL中,值“ NewUnitPhaseStatus”存储为int。 如果我只是返回查询,那么当我尝试提取该值时,它只是说DBcontext已被处置。 但是,如果我尝试将查询结果转换为列表,则表示无法将int转换为类型NewUnitPhaseStatus(枚举类型)。
public IEnumerable<UnitPhaseLog> GetAllForUnitPhase(long unitPhaseId)
{
using (var db = new DbContext(_connStringKey))
{
var querys = from s in db.UnitPhaseLogs
where s.UnitPhaseId == unitPhaseId
select s;
return querys;
}
}
如果使用foreach语句将每一行转换为一个枚举,则它们会出错,因为var查询属于UnitPhaseLog类,而NewUnitPhaseStatus等于枚举。
错误信息:
如果尝试将结果转换为列表。
无法将“ UnitPhaseLog”上的“ NewUnitPhaseStatus”属性设置为“ System.Int64”值。 您必须将此属性设置为'Core.UnitPhaseStatus'类型的非空值。
如果尝试只返回查询结果本身:
由于已处置DbContext,因此无法完成该操作。
码:
public enum UnitPhaseStatus
{
[Display(Name = "No Status")]
NoStatus,
[Display(Name = "Not Ready")]
NotReady,
[Display(Name = "Materials Needed")]
MaterialsNeeded,
[Display(Name = "Ready For Work")]
ReadyForWork,
[Display(Name = "Work In Progress")]
WorkInProgress,
[Display(Name = "Ready")]
ReadyForQc,
[Display(Name = "Approved")]
Approved,
[Display(Name = "Rejected")]
Rejected,
}
您需要将数据库的返回值强制转换为枚举类型。
unit.NewUnitPhaseStatus = (UnitPhaseStatus)UnitPhaseStatus;
不过,您可以直接执行此操作,而不必经历额外的局部变量。
因此,代替:
UnitPhaseStatus UnitPhaseStatus = query.NewUnitPhaseStatus;
unit.NewUnitPhaseStatus = UnitPhaseStatus;
您可以使用:
unit.NewUnitPhaseStatus = (UnitPhaseStatus)query.NewUnitPhaseStatus;
这是假设您使用的是Entity Framework,因此如果您不这样做,请随时忽略。
不必担心将Int转换为枚举,也不必担心将枚举转换为Int,更好的解决方案可能是更改Entity以将该列直接绑定到枚举,并让框架为您完成转换。
您无需弄乱那个foreach
循环-您的querys
已经是正确的类型,因此,如果它不为null
,则只需返回该值即可。
public IEnumerable<UnitPhaseLog> GetAllForUnitPhase(long unitPhaseId)
{
using (var db = new DbContext(_connStringKey))
{
var querys = from s in db.UnitPhaseLogs where s.UnitPhaseId == unitPhaseId select s;
List<UnitPhaseLog> UnitPhaseLogList = new List<UnitPhaseLog>();
if (null == querys) return UnitPhaseLogList;
return querys;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.