我如何使用 link 和 Entity Framework 阅读一对多 linked table?

How could I read one to many linked table using link with Entity Framework?

我是 Entity Framework 和 Linq (Visual Studio 2017 - EF 5.0) 的新手。目前,我可以毫无问题地阅读 tables,但想知道如何阅读链接的 table。 我目前的功能可以做到这一点,但肯定有一种比我开发的两步阅读更简单的方法。

public override List<CartItem> GetMyCartOrderItems(int UserID)
    {
        try
        {
            using (foodorderingdbEntities oMConnection = new foodorderingdbEntities())
            {

                var oCart = oMConnection.carts.SingleOrDefault(p => p.USER_ID == UserID);
                if (oCartItems != null)
                {
                    int CartID = oCart.CART_ID;
                    var oCartItems = oMConnection.cart_item.Where(p => p.CART_ITEM_CART_ID == CartID);
                    if (oCartItems != null)
                    {
                        List<CartItem> oRecList = new List<CartItem>();
                        foreach (cart_item oDBrec in oCartItems)
                        {
                            CartItem oRec = new CartItem();
                            oRec.CartID = oDBrec.CART_ITEM_ID;
                            oRec.CartItemID = oDBrec.CART_ITEM_CART_ID;
                            oRec.DateTime = oDBrec.CART_ITEM_ADDED_DATE_TIME;
                            oRec.SystemComments = oDBrec.CART_ITEM_SYSTEM_COMMENTS;
                            oRecList.Add(oRec);
                        }
                        return oRecList;
                    } 
                else { return null; }
                }
                else { return null; }
            }
        }
        catch (Exception ex)
        {
            //IBLogger.Write(LOG_OPTION.ERROR, "File : MHCMySQLDataConection.cs, Method : GetPatientByID(1), Exception Occured :" + ex.Message + Environment.NewLine + "Trace :" + ex.StackTrace);
            return null;
        }
    }

您可以看到我使用 UserID 从购物车 table 获取购物车 ID,然后我使用 CartID 从 Cart_Item table 检索购物车商品。 Cart_Item_Cart_ID 是 cart_item table 中的外键。 (这是一对多table)

这就是我的想法,但显然行不通。

List<cart_item> oCartItems = oMConnection.carts.SingleOrDefault(c => c.USER_ID == UserID).cart_item.Where(p => p.CART_ITEM_CART_ID = c.CART_ID).ToList<cart_item>();

有什么帮助吗?

我的实体关系

public partial class cart
{
    public cart()
    {
        this.cart_item = new HashSet<cart_item>();
    }

    public int CART_ID { get; set; }
    public int USER_ID { get; set; }
    public decimal ORDER_TOTAL_COST { get; set; }

    public virtual ICollection<cart_item> cart_item { get; set; }
    public virtual user user { get; set; }
}

因为您的查询有多个级别的一对多关系,而您只想要 cart_items,像这样换个方向更容易:

var oCart = oMConnection.cart_item
  .Where(c=>c.cart.user.USER_ID == UserID);

按照您的方法应该也可以,但是您需要使用 SelectMany 而不是 select,如下所示:

var oCartItems = oMConnection.carts
  .Where(c=>c.USER_ID==UserID)
  .SelectMany(c=>c.cart_item);