簡體   English   中英

context.ToListAsync() 沒有從表中獲取任何數據

[英]context.ToListAsync() is not getting any data from the table

該表是在我為“AssetResource”創建 DBSet 之前創建的。 由於我想使用 EF 使其更易於插入或更新,因此我創建了DbSet<AssetResource>而沒有調用添加遷移。 該表中已經有一些數據,但是當我調用它時

var list = await context.AssetSources.ToListAsync();

我得到Data is Null然后轉到異常。

我嘗試添加遷移並成功創建它,但是當我命令update-database時,它告訴我 Resources 表已經存在,這實際上是正確的,因為這個表是在我創建DbSet<AssetResource>之前創建的。

這是獲取列表的完整代碼:

public async Task<IEnumerable<AssetSource>> GetAssetResources()
        {
            var lAssetSource = new List<AssetSource>();
            try
            {
                var sw = new Stopwatch();
                if (cache.TryGetValue(CACHE_KEYASSETSOURCE, out List<AssetSource> refListAssetSource))
                {
                    helper.LogMessage("Assets Sources are found in cache", LoggerModel.LoggingType.Information);
                    lAssetSource = refListAssetSource;
                }
                else
                {
                    var l = await context.AssetSources.ToListAsync();
                }
                return lAssetSource;
            }
            catch (Exception e)
            {
                helper.LogMessage(e.Message, Shared.Models.LoggerModel.LoggingType.Error);
                throw new NoObjectDetectedException(e.Message);
            }
        }

Data is null表示實體框架嘗試將可為空的 db 列綁定到不可為空的屬性。 確保如果 db 列是例如int, null實體 model 在 c# 是int? 而不是int

手動刪除表,然后運行update-database命令,應該就可以了。 如果刪除表,則在運行update-database命令時表中將沒有數據。 一個好主意是在運行命令之前重命名現有表,這樣您仍然可以在重命名的表中保留現有數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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