zoukankan      html  css  js  c++  java
  • EF的表连接方法Include()

    在EF中表连接常用的有Join()和Include(),两者都可以实现两张表的连接,但又有所不同。

    例如有个唱片表Album(AlbumId,Name,CreateDate,GenreId),表中含外键GenreId连接流派表Genre(GenreId,Name)。每个唱片归属唯一一个流派,一个流派可以对应多个唱片。

    1.Join(),两表不必含有外键关系,需要代码手动指定连接外键相等(具有可拓展性,除了值相等,还能指定是>,<以及其他对两表的相应键的关系),以及结果字段。

    重载方式(是扩展方法,第一个参数带this,代表自身):

    1.public static IQueryable<TResult> Join<TOuter, TInner, TKey, TResult>(this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<TOuter, TInner, TResult>> resultSelector);
    
    2.public static IQueryable<TResult> Join<TOuter, TInner, TKey, TResult>(this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<TOuter, TInner, TResult>> resultSelector, IEqualityComparer<TKey> comparer);

    那么可以这么写两个表的连接:

    var wholeRecord = dc.Album.Join(dc.Genre, a => a.GenreId, g => g.GenreId, (a, g) => new { a.AlbumId,a.Name,g.GenreId,g.Name;

    这样就选取除了两表的AlbumId,Name,GenreId,Name。

    2.Include(),两表必须含有外键关系,只需要指定键名对应的类属性名即可,不需指定结果字段(即全部映射)。默认搜索某表时,不会顺带查询外键表,直到真正使用时才会再读取数据库查询;若是使用 Include(),则会在读取本表时把指定的外键表信息也读出来。

    重载方式:

    //位于namespace System.Data.Entity.Infrastructure
    public DbQuery<TResult> Include(string path);
    //位于namespace System.Data.Entity,务必引入才能找到该方法。否则只看到上个方法
    public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> source, Expression<Func<T, TProperty>> path) where T : class;
            public static IQueryable<T> Include<T>(this IQueryable<T> source, string path) where T : class;

    可以这么写:

    //EF已经生成了Album和Genre的数据库映射模型类以及导航属性
    var wholeRecord=dc.Album.Include("Genre");
    //或者
    //var wholeRecord=dc.Album.Include(a=>Genre);

    这样数据库就执行了一个左连接,把Album和Genre的所有字段全部连起来了,并且Include()是立即查询的,像ToList()一样,不会稍后延迟优化后再加载。

    这样其实效率很低,因为如果两张表记录很大,那么连接是个费时费资源的事情,建议少用,或者先筛选出需要的结果集再连接。

  • 相关阅读:
    C++Primer 中间Sales_items.h头文件
    2014最不受欢迎10编程语言种
    解决ubuntu 14.04删ibus导致系统设置项目的损失后,,退出关机问题是不正常的
    会计翻译成英文
    Delphi 使用 Format格式话字符串的用法
    浅谈暂估应付账款的会计处理
    Delphi TcxTreelist 设置scrollbars 不起作用的原因
    Delphi 调试 通过BreakPoint
    折现率”的公式
    考会计证 需要的科目
  • 原文地址:https://www.cnblogs.com/nlh774/p/3588286.html
Copyright © 2011-2022 走看看