【问题标题】:LINQ: Prefetching data from a second tableLINQ:从第二个表中预取数据
【发布时间】:2010-11-30 03:05:41
【问题描述】:

我正在尝试使用 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();

Customer 类如下所示:

[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'。”

我显然是在错误地处理这个问题。任何指向正确方向的指针都会很有帮助。

【问题讨论】:

    标签: c# linq linq-to-sql


    【解决方案1】:

    正如它所说,你不能在那里构造一个客户。

    (可以说)最简单的做法是创建一个封装您需要的属性的新类。您可以通过以下方式从 Customer 类中获取所有内容:

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

    【讨论】:

      【解决方案2】:

      如果你想做正版预加载,可以这样做:

      (假设您的数据库中的 CustomerCustomerType 表之间存在连接,并且 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;
      

      然后您可以访问TypeName(其中cCustomerresults):

      c.CustomerType.TypeName;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-01
        • 2018-07-13
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        • 2012-08-13
        • 1970-01-01
        相关资源
        最近更新 更多