Reputation: 115
How to return IEnumerable
with NewUnitPhaseStatus
as an enum?
In SQL the value "NewUnitPhaseStatus" is stored as an int. If I just return the query, then when I try to extract the value it just says that the DBcontext has been disposed. But If I try to convert the query result into a list, then it says that int cannot be converted to type NewUnitPhaseStatus(the enum type).
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;
}
}
If one uses a foreach statement to convert each row into an enum, they get an error because var query is of class UnitPhaseLog with NewUnitPhaseStatus equal to enum.
Error message:
If one tries to convert the results to a list.
The 'NewUnitPhaseStatus' property on 'UnitPhaseLog' could not be set to a 'System.Int64' value. You must set this property to a non-null value of type 'Core.UnitPhaseStatus'.
If one tries to just return the query results themselves:
The operation cannot be completed because the DbContext has been disposed.
Code:
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,
}
Upvotes: 0
Views: 3942
Reputation: 1184
There is no need for you to mess with that foreach
loop - your querys
is already of the right type, so if it isn't null
, just return that.
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;
}
}
Upvotes: 1
Reputation: 147
This is assuming you're using Entity Framework, so if you're not doing so feel free to ignore.
Rather than worry about casting an Int to an enum, or an enum to an Int, a better solution might be to change the Entity to bind that column directly to the enum and letting the framework do the conversion for you.
Upvotes: 1
Reputation: 1184
You need to cast the return value from the database to the enum type.
unit.NewUnitPhaseStatus = (UnitPhaseStatus)UnitPhaseStatus;
Though, you can do this directly, instead of having to go through an extra local variable.
So, instead of:
UnitPhaseStatus UnitPhaseStatus = query.NewUnitPhaseStatus;
unit.NewUnitPhaseStatus = UnitPhaseStatus;
You can use:
unit.NewUnitPhaseStatus = (UnitPhaseStatus)query.NewUnitPhaseStatus;
Upvotes: 2