简体   繁体   中英

Handling empty collections in Entity Framework

I fill up a List in Entity Framework;

    List<StockProperties> props = db.StockProperties
                                    .Where(prop => prop.Stok_ID == stok.ID)
                                    .ToList();

The problem here is if my query is null, it returns a

Non-static method requires a target.

error which is obvious since EF does that with empty sequences.My question is what is the most reasonable way to handle these null queries?I want my list to be empty if my query returns null sequences.

This:

List<StockProperties> props = db.StockProperties
                                .Where(prop => false)

Is returning a System.Linq.Enumerable.WhereListIterator<StockProperties> with 0 reccords it will never be null .

Your problem may be with prop => prop.Stok_ID == stok.ID

Do stok is declared?

Check here

You can supply a fall back option for null

var props = 
    db.StockProperties.Where(prop => prop.Stok_ID == stok.ID)
    ?? Enumerable.Empty<StockProperties>();

or

var props = 
    db.StockProperties.Where(prop => prop.Stok_ID == stok.ID).ToList()
    ?? new List<StockProperties>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM