簡體   English   中英

從SQL查詢C#實體框架將int轉換為枚舉

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM