简体   繁体   中英

entity framework select records do not exists in join table or field is null

I am building an c# lambda with Entity Framework

I have two tables with inner join relationship...( Order and MarketOrder ). OrderID is the PK on Order Table and the FK on MarketOrder Table.

Resuming my Model is like this

  public class Order { [Key] public int OrderID { get; set; } public virtual MarketOrder MarketOrders { get; set; } } public class MarketOrder { [Key] public int MarketOrderID { get; set; } // One sequence for all system market orders. public int OrderID { get; set; } public virtual Order Order { get; set; } } 

I need to select records do not exists in join table or is exists having field MarketOrder.Status is null

I taste this

db.Order
.Where(c => !db.MarketOrder
    .Select(b => b.OrderID)
    .Contains(c.OrderID)
);

I works fine when do not exists in other table but I can not use it in case it exists with Status == null.

Whe the relationship is One to Many. In Order class I have the property

 public virtual List<MarketOrder> MarketOrders { get; set; }

var aa =(from order in db.OrderFunds
from marketOrder in order.MarketOrders.DefaultIfEmpty()
where marketOrder.OrderID == null || marketOrder.Status == null).ToList();

it Works fine.

I have the problem when the relationship is One To One . In Order Class I have the property

 public virtual MarketOrder MarketOrders { get; set; }

the line

order.MarketOrders.DefaultIfEmpty()

Does not work. order.MarketOrders do not have the method DefaultIfEmpty() . If I use order.MarketOrders.ToString().DefaultIfEmpty() The clause where marketOrder.OrderID do not have property OrderID

How can I solved it.

Thanks.

db.Order.Where(o => o.MarketOrder?.Status == null)

如同

db.Order.Where(o => o.MarketOrder == null || o.MarketOrder.Status == null)

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