簡體   English   中英

在實體框架中聯接兩個表

[英]joining two tables in entity framework

我正在嘗試在實體框架中加入兩個表,並從其中一個表中獲取值,以對第三個表進行另一個查詢,這就是我正在使用的查詢

  var fav = from favs in db.FAVORITES

                      join pins in db.PINS
                      on new { favs.USER_ID, favs.PIN_ID } equals new { userId, pins.PIN_ID } into res
                      from r in res
                      select new { favs.PIN_ID, r.TYPE_ID };

但是它給我帶來了語法錯誤。join子句中的表達式之一的類型不正確。 在對“ GroupJoin”的調用中類型推斷失敗,我已經搜索了該錯誤,發現人們總是說要確保equals子句中的屬性是同一類型,是的,所有類型都是非可空int

進行LINQ連接時,equals兩側的類型必須完全相同,但是在查詢中您具有USER_ID和userId。

解決方法很簡單:

 var fav = from favs in db.FAVORITES
           join pins in db.PINS
               on new { favs.USER_ID, favs.PIN_ID } 
               equals 
               // use explicit naming so the first property gets the name USER_ID not userId
               new { USER_ID = userId, pins.PIN_ID } 
               into res
           from r in res
           select new { favs.PIN_ID, r.TYPE_ID };

如果使用GroupJoin的流利語法(為什么要在這里實際執行操作,由於使用了“ into”子句;常規Join與此類似),那么為什么需要這樣做很容易。

簽名是:

public static IQueryable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
    this IQueryable<TOuter> outer,
    IEnumerable<TInner> inner,
    Expression<Func<TOuter, TKey>> outerKeySelector,
    Expression<Func<TInner, TKey>> innerKeySelector,
    Expression<Func<TOuter, IEnumerable<TInner>, TResult>> resultSelector
)

請注意,outerKeySelector和innerKeySelector必須返回相同的TKey類型(然后通過匹配這些鍵來完成連接)。

要以流利的風格編寫原始聯接,您需要:

var fav = db.FAVORITES.GroupJoin(
    inner: inner,
    // the return types of the selectors don't match, so the compiler can't
    // infer a type for TKey!
    outerKeySelector: favs => new { favs.USER_ID, favs.PIN_ID },
    innerKeySelector: pins => new { userId,       pins.PIN_ID },
    resultSelector: (favs, res) => res.Select(r => new { favs.PIN_ID, r.TYPE_ID })
)
.SelectMany(res => res);

您可以嘗試以下方法:

var balance = (from a in context.Accounts
           join c in context.Clients on a.UserID equals c.UserID
           where c.ClientID == yourDescriptionObject.ClientID
           select a.Balance)
          .SingleOrDefault();

或-如果您只有DescriptionID:

var balance = (from a in context.Accounts
           join c in context.Clients on a.UserID equals c.UserID
           join d in context.Descriptions on c.ClientID equals d.ClientID
           where d.DescriptionID == yourDescriptionID
           select a.Balance)
          .SingleOrDefault();

(或FirstOrDefault()ToList()Sum()嗎?因為您的模型將允許客戶/描述與多個帳戶相關)

暫無
暫無

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

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