C# LINQ:从第二个表预取数据

C# LINQ:从第二个表预取数据,c#,linq,linq-to-sql,C#,Linq,Linq To Sql,我正在尝试使用linq查询预取一些外键数据。下面是一个简单的例子来解释我的问题: var results = (from c in _customers from ct in _customerTypes where c.TypeId == ct.TypeId select new Customer {

我正在尝试使用linq查询预取一些外键数据。下面是一个简单的例子来解释我的问题:

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();
但是,LINQ不允许您使用“不允许在查询中显式构造实体类型‘Customer’的NotSupportedException”来执行此操作


很明显,我的做法是错误的。任何指向正确方向的指针都会非常有用。

正如它所说的,你不能在那里构建客户

(可以说)最简单的方法是创建一个封装所需属性的新类。通过这样做,您可以从Customer类获得一切:

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

正如它所说的,你不能在那里建立一个客户

(可以说)最简单的方法是创建一个封装所需属性的新类。通过这样做,您可以从Customer类获得一切:

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

如果要进行正版预加载,可以执行以下操作:

(这假设数据库中的
Customer
CustomerType
表之间存在连接,并且LINQ to SQL知道这一点。)


如果要进行正版预加载,可以执行以下操作:

(这假设数据库中的
Customer
CustomerType
表之间存在连接,并且LINQ to SQL知道这一点。)

MyDataContext dc = new MyDataContext(); // Use your application-specific DataContext class
DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.LoadWith<Customer>(c => c.CustomerType);
dc.LoadOptions = loadOptions;
var results = from c in dc.GetTable<Customer>() select c;
c.CustomerType.TypeName;