簡體   English   中英

使用 EF CORE 檢索可為 null 的 object

[英]Retrieve nullable object using EF CORE

我是初學者,在測試一些代碼時,我似乎無法理解如何正確執行此操作。

第一:我有一個城市 class:

public class City
{
    public City()
    {
        ZipCode = "";
        Name = "";
    }

    public int Id { get; set; }
    public string ZipCode { get; set; }
    public string Name { get; set; }
}

第二:我有一個聯系人 class,它使用可為空的城市 class(以防用戶不知道城市):

public class Contact
{
    public Contact()
    {
        Name = "";
        Line1 = "";
        Line2 = "";
        CityId = null;
        City = new City();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }

    private int? _CityId;
    public int? CityId
    {
        get { return _CityId; }
        set { _CityId = value < 1 ? null : value; }
    }

    private City _City;
    public City City
    {
        get { return _City; }
        set { _City = _CityId == null ? null : value; }
    }
}

我遇到的問題當我檢索存儲了 null City的記錄時(當檢索記錄且其 City 不是 null 時,一切正常)。 My.Select() 語句如下所示:

var result = await _context.Contact
            .Where(w => w.Id == id)
            .Include(q => q.City)
            .Select(s => new Contact
            {
                // Entity
                Id = s.Id,
                // Model
                Line1 = s.Line1,
                Line2 = s.Line2,
                CityId = s.CityId,
                City = new City // I am retrieving this so that I can get the inner data as well
                {
                    // Entity
                    Id = s.City.Id,
                    // Model
                    ZipCode = s.City.ZipCode,
                    Name = s.City.Name,
                }
            }).FirstOrDefaultAsync();

output 適用於沒有 null 城市的記錄,但如果用戶檢索帶有 null 城市的記錄,則會拋出以下錯誤

可為空的 object 必須有一個值。

誰能教我如何正確地做到這一點? 先感謝您!

您不需要使用 Select 創建新實體,您會收到錯誤消息,因為如果 s.City 為 null,則 s.City.Id 不存在。 Insteat直接使用搜索

var result = await _context.Contact
            .Include(q => q.City)
            .FirstOrDefaultAsync(x => x.Id == id);

為什么你用Select ,用私有財產給城市

聯系電話 Class:

public class Contact
{
    public Contact()
    {
        Name = "";
        Line1 = "";
        Line2 = "";
        CityId = null;
        City = new City();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }

    public int? CityId;
    public City City
    
}

你的Select和實體class是一樣的,你不用用。

var result = await _context.Contact
            .Include(q => q.City)
            .FirstOrDefaultAsync(f => f.Id == id);

謝謝大家的解答!

我發現罪魁禍首是這行代碼(感謝您的回答和解釋):

Id = s.City.Id

這是因為這里的Id是一個int不可為 null,因為這是 MSSQL 中的一個身份)但是當CityId以及 City object )在數據庫中存儲null時, s.City.Id也將在 .Select() 中包含null .

上述情況下的Id = s.City.Id失敗,因為Id不可為空)被迫接收null包含在 s.City.Id 中)。

暫無
暫無

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

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