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

  • Home
  • SEARCH
  • 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 8747887
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T12:25:55+00:00 2026-06-13T12:25:55+00:00

Is it possible to perform a LinQ select by PK dynamically ? Something like

  • 0

Is it possible to perform a LinQ select by PK dynamically ?

Something like that :

public T FindByPK(IEnumerable<T> table, T itemToFind)
{

}

T is a mapping from table (LinQ to SQL autogenerated).

I tryed using reflection but I don’t know how to get the attribute “IsPrimaryKey” and then perform the LinQ because sometimes the PK contains more than one column.

EDIT after Answer by chridam

So, I can now do a GetByPK but it assumes that the PK is only one column…

public static class DataContextHelpers
{
    public static T GetByPk<T>(this DataContext context, object pk) where T : class {
        var table = context.GetTable<T>();
        var mapping = context.Mapping.GetTable(typeof(T));
        var pkfield = mapping.RowType.DataMembers.SingleOrDefault(d => d.IsPrimaryKey);
        if (pkfield == null)
            throw new Exception(String.Format("Table {0} does not contain a Primary Key field", mapping.TableName));
        var param = Expression.Parameter(typeof(T), "e");
        var predicate = Expression.Lambda<Func<T, bool>>(Expression.Equal(Expression.Property(param, pkfield.Name), Expression.Constant(pk)), param);
        return table.SingleOrDefault(predicate);
    }
}

I changed the code like this to be able to get all columns of the primary keys and also, the object pk has to be a row of the table (because I don’t know what are the pk columns)

public static T GetByPk<T>(this DataContext context, T row) where T : class
        {
            var table = context.GetTable<T>();
            var mapping = context.Mapping.GetTable(typeof(T));

            var pkfield = mapping.RowType.DataMembers.Where(d => d.IsPrimaryKey);
            if (!pkfield.Any())
                throw new Exception(String.Format("Table {0} does not contain a Primary Key field", mapping.TableName));
            var param = Expression.Parameter(typeof(T), "e");
            var predicate = Expression.Lambda<Func<T, bool>>(Expression.Equal(Expression.Property(param, pkfield??), Expression.Property(param, row??)), param);
            return table.SingleOrDefault(predicate);
        }

So, I am stuck at Expression.Property who need only one property and not a group of many.

  • 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. Editorial Team
    Editorial Team
    2026-06-13T12:25:56+00:00Added an answer on June 13, 2026 at 12:25 pm

    You could try writing an extension method onto your DataContext object that facilitates the pulling of records from the database by their Primary Key, as outlined by Chris Sainty in his blog post LINQ to SQL: Generic Primary Key function :

    public static class DataContextHelpers
    {
        public static T GetByPk<T>(this DataContext context, object pk) where T : class {
            var table = context.GetTable<T>();
            var mapping = context.Mapping.GetTable(typeof(T));
            var pkfield = mapping.RowType.DataMembers.SingleOrDefault(d => d.IsPrimaryKey);
            if (pkfield == null)
                throw new Exception(String.Format("Table {0} does not contain a Primary Key field", mapping.TableName));
            var param = Expression.Parameter(typeof(T), "e");
            var predicate = Expression.Lambda<Func<T, bool>>(Expression.Equal(Expression.Property(param, pkfield.Name), Expression.Constant(pk)), param);
            return table.SingleOrDefault(predicate);
        }
    }
    

    Then call the method by way of:

    MyDataContext db = new MyDataContext();
    Product p = db.GetByPk<Product>(1);
    

    You might also want to have a look at Denis Troller’s answer as an alternative.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to perform LINQ to SQL mapping in C#, in a many-to-many
Is it possible to perform some custom processing when Windsor instantiates a type? Something
Is it possible to perform a request that checks the string representation of a
Is it somehow possible to chain together several LINQ queries on the same IEnumerable
It's possible to perform joins across different databases using LINQ? If yes then how?
I am trying to perform a query using Linq, something I am new to.
Is it even possible to perform address (physical, not e-mail) validation? It seems like
Possible Duplicate: LINQ: How to perform .Max() on a property of all objects in
I have a List/IEnumerable of objects and I'd like to perform a calculation on
Is it possible to perform a group by on an object? from item in

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.