【问题标题】:How can I load class's part using linq to sql without anonymous class or additional class?如何在没有匿名类或附加类的情况下使用 linq to sql 加载类的部分?
【发布时间】:2010-06-10 10:23:33
【问题描述】:
class Test { 
  int Id{get;set;} 
  string Name {get;set;} 
  string Description {get;set;}
}

//1)ok
context.Tests.Select(t => new {t.Id, t.Name}).ToList().Select(t => new Test{Id = t.Id,
Name = t.Name});

//2)ok
class TestPart{
  int Id{get;set;}
  string Name {get;set;}
}
context.Tests.Select(t => new TestPart{Id = t.Id,
Name = t.Name}).ToList().Select(t => new Test{Id = t.Id,
Name = t.Name});

//3)error Explicit construction of entity type 'Test' in query is not allowed.
context.Tests.Select(t => new Test{Id = t.Id,
Name = t.Name}).ToList();

有没有办法使用第三种变体?

【问题讨论】:

    标签: .net linq linq-to-sql anonymous-class


    【解决方案1】:

    如果您的 Test 类不用于写入数据,您可以通过删除 dbml 中的主键来禁用对象跟踪。如果没有跟踪 Test 实例的更改,那么您可以在查询中随意更新任意数量的实例。

    http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/1ce25da3-44c6-407d-8395-4c146930004b

    假设您想要一个可以部分加载的 Test 类,以及一个可以写回的 Test 类。只需将 Test 表放到设计器上两次,然后从其中一个中删除主键。

    【讨论】:

      【解决方案2】:

      在 TestPart 或 Test 上提供隐式转换应该可以解决问题。您可能还想考虑从 TestPart 派生 Test,因为 Test 只是扩展 TestPart。这样,您不必定义隐式转换。

      【讨论】:

        猜你喜欢
        • 2012-07-19
        • 1970-01-01
        • 1970-01-01
        • 2015-10-04
        • 2010-12-29
        • 1970-01-01
        • 2014-12-12
        • 2011-05-21
        • 1970-01-01
        相关资源
        最近更新 更多