Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 169935
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T12:43:08+00:00 2026-05-11T12:43:08+00:00

I wrote the following method. public T GetByID(int id) { var dbcontext = DB;

  • 0

I wrote the following method.

public T GetByID(int id) {     var dbcontext = DB;     var table = dbcontext.GetTable<T>();     return table.ToList().SingleOrDefault(e => Convert.ToInt16(e.GetType().GetProperties().First().GetValue(e, null)) == id); } 

Basically it’s a method in a Generic class where T is a class in a DataContext.

The method gets the table from the type of T (GetTable) and checks for the first property (always being the ID) to the inputted parameter.

The problem with this is I had to convert the table of elements to a list first to execute a GetType on the property, but this is not very convenient because all the elements of the table have to be enumerated and converted to a List.

How can I refactor this method to avoid a ToList on the whole table?

[Update]

The reason I can’t execute the Where directly on the table is because I receive this exception:

Method ‘System.Reflection.PropertyInfo[] GetProperties()’ has no supported translation to SQL.

Because GetProperties can’t be translated to SQL.

[Update]

Some people have suggested using an interface for T, but the problem is that the T parameter will be a class that is auto generated in [DataContextName].designer.cs, and thus I cannot make it implement an interface (and it’s not feasible implementing the interfaces for all these ‘database classes’ of LINQ; and also, the file will be regenerated once I add new tables to the DataContext, thus loosing all the written data).

So, there has to be a better way to do this…

[Update]

I have now implemented my code like Neil Williams‘ suggestion, but I’m still having problems. Here are excerpts of the code:

Interface:

public interface IHasID {     int ID { get; set; } } 

DataContext [View Code]:

namespace MusicRepo_DataContext {     partial class Artist : IHasID     {         public int ID         {             get { return ArtistID; }             set { throw new System.NotImplementedException(); }         }     } } 

Generic Method:

public class DBAccess<T> where T :  class, IHasID,new() {     public T GetByID(int id)     {         var dbcontext = DB;         var table = dbcontext.GetTable<T>();          return table.SingleOrDefault(e => e.ID.Equals(id));     } } 

The exception is being thrown on this line: return table.SingleOrDefault(e => e.ID.Equals(id)); and the exception is:

System.NotSupportedException: The member 'MusicRepo_DataContext.IHasID.ID' has no supported translation to SQL.

[Update] Solution:

With the help of Denis Troller‘s posted answer and the link to the post at the Code Rant blog, I finally managed to find a solution:

public static PropertyInfo GetPrimaryKey(this Type entityType) {     foreach (PropertyInfo property in entityType.GetProperties())     {         ColumnAttribute[] attributes = (ColumnAttribute[])property.GetCustomAttributes(typeof(ColumnAttribute), true);         if (attributes.Length == 1)         {             ColumnAttribute columnAttribute = attributes[0];             if (columnAttribute.IsPrimaryKey)             {                 if (property.PropertyType != typeof(int))                 {                     throw new ApplicationException(string.Format('Primary key, '{0}', of type '{1}' is not int',                                 property.Name, entityType));                 }                 return property;             }         }     }     throw new ApplicationException(string.Format('No primary key defined for type {0}', entityType.Name)); }  public T GetByID(int id) {     var dbcontext = DB;      var itemParameter = Expression.Parameter(typeof (T), 'item');     var whereExpression = Expression.Lambda<Func<T, bool>>         (         Expression.Equal(             Expression.Property(                  itemParameter,                  typeof (T).GetPrimaryKey().Name                  ),             Expression.Constant(id)             ),         new[] {itemParameter}         );     return dbcontext.GetTable<T>().Where(whereExpression).Single(); } 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T12:43:09+00:00Added an answer on May 11, 2026 at 12:43 pm

    What you need is to build an expression tree that LINQ to SQL can understand. Assuming your ‘id’ property is always named ‘id’:

    public virtual T GetById<T>(short id) {     var itemParameter = Expression.Parameter(typeof(T), 'item');     var whereExpression = Expression.Lambda<Func<T, bool>>         (         Expression.Equal(             Expression.Property(                 itemParameter,                 'id'                 ),             Expression.Constant(id)             ),         new[] { itemParameter }         );     var table = DB.GetTable<T>();     return table.Where(whereExpression).Single(); } 

    This should do the trick. It was shamelessly borrowed from this blog. This is basically what LINQ to SQL does when you write a query like

    var Q = from t in Context.GetTable<T)()         where t.id == id         select t; 

    You just do the work for LTS because the compiler cannot create that for you, since nothing can enforce that T has an ‘id’ property, and you cannot map an arbitrary ‘id’ property from an interface to the database.

    ==== UPDATE ====

    OK, here’s a simple implementation for finding the primary key name, assuming there is only one (not a composite primary key), and assuming all is well type-wise (that is, your primary key is compatible with the ‘short’ type you use in the GetById function):

    public virtual T GetById<T>(short id) {     var itemParameter = Expression.Parameter(typeof(T), 'item');     var whereExpression = Expression.Lambda<Func<T, bool>>         (         Expression.Equal(             Expression.Property(                 itemParameter,                 GetPrimaryKeyName<T>()                 ),             Expression.Constant(id)             ),         new[] { itemParameter }         );     var table = DB.GetTable<T>();     return table.Where(whereExpression).Single(); }   public string GetPrimaryKeyName<T>() {     var type = Mapping.GetMetaType(typeof(T));      var PK = (from m in type.DataMembers               where m.IsPrimaryKey               select m).Single();     return PK.Name; } 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 76k
  • Answers 76k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • added an answer Yes, just remove the $this->htmlEscape() and leave the $_option->getTitle() The… May 11, 2026 at 3:14 pm
  • added an answer (s, e) is the Method Parameter Signature for the event… May 11, 2026 at 3:14 pm
  • added an answer You could possiblly create a new Login control that inherits… May 11, 2026 at 3:14 pm

Related Questions

I just wrote an if statement in the lines of if (value == value1
I wrote a program which includes writing and reading from database. When I run
I wrote a small PHP application several months ago that uses the WordPress XMLRPC
I have a Visual Studio 2008 solution with two projects (a Word-Template project and

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.