Entity Framework 多个 table 与 linq

Entity Framework multiple table with linq

对于代码优先模型:

public class User
{
    [Key]
    public long Id { get; set; }
    public virtual List<Address> Addresses { get; set; }
    public string UserName { get; set; }
} 

public class Address
{
    [Key]
    public long Id { get; set; }
    public string Reference { get; set; }
    public string Street { get; set; }
}

我先从代码创建了 entity framework 模型。它工作正常。现在我想使用 linq 为用户 table 查询 select。

public IEnumerable GetLicensee()
{
    using (var db = new DataModelContext())
    {
        IEnumerable query = (from b in db.User
                             select new { UserName= b.UserName,Address=b.Addresses }).ToList();

        return query;
    }
}

它没有返回地址 table,只有 returns 用户名。

EF 默认开启延迟加载,因此您需要通过调用使用预加载 Include(),此方法也获取相关实体,在您的情况下 Include("Addresses") 方法获取相关 Adressess

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method.

public IEnumerable GetLicensee()
{
        using (var db = new DataModelContext())
        {
        IEnumerable query = (from b in db.User.Include("Addresses")
                     select new { UserName= b.UserName,Address=b.Addresses }).ToList();

            return query;
        }
 }

这里找到more