LINQ:从第二个表中预取数据 [英] LINQ: Prefetching data from a second table

查看:81
本文介绍了LINQ:从第二个表中预取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用linq查询预取一些外键数据.一个简短的例子来解释我的问题,如下:

I'm trying to pre-fetch some foreign key data using a linq query. A quick example to explain my problem follows:

var results = (from c in _customers
               from ct in _customerTypes 
               where c.TypeId == ct.TypeId 
               select new Customer
                          {
                             CustomerId = c.CustomerId,
                             Name = c.Name,
                             TypeId = c.TypeId,
                             TypeName = ct.TypeName,  <-- Trying to Prefetch this
                          }).ToList();

Customer类如下:

The Customer class looks like:

[Table(Name = "Customers")]
public class Customer
{
   [Column(Name = "CustomerId", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
   public int CustomerId { get; set; }

   [Column(Name = "Name")]
   public string Name { get; set; }

   [Column(Name = "TypeId")]
   public int TypeId { get; set;}

   public string TypeName { get; set; }

   public Confession (){}
}

但是LINQ不允许您抛出NotSupportedException与不允许在查询中显式构造实体类型'Customer'的情况."

However LINQ will not let you do this throwing a NotSupportedException with "Explicit construction of entity type 'Customer' in query is not allowed."

我显然在错误地处理此问题.任何指向正确方向的指针都将最有帮助.

I'm clearly approaching this incorrectly. Any pointers in the right direction would be most helpfull.

推荐答案

正如所说的,您不能在那里建立客户.

As it says, you can't construct a Customer there.

(可以说)最简单的方法是创建一个新类,该类封装所需的属性.您可以通过以下方式从Customer类中获取所有信息:

The (arguably) easiest thing to do would be to create a new class that encapsulates the properties you need. You can get everything from the Customer class by doing it like this:

var results = (from c in _customers
               from ct in _customerTypes 
               where c.TypeId == ct.TypeId 
               select new
                      {
                         Customer = c,
                         TypeName = ct.TypeName
                      }).ToList();

这篇关于LINQ:从第二个表中预取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆