Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to pass in a generic entity and access a common property?

Tags:

c#

linq

generics

I want to have a method that checks some AccountIDs are allowed for a certain operations and in doing so, I need to get a distinct list of AccountIDs in any entity type that I pass through.

I could have a User entity, a Transaction entity, and Product entity, etc. but they will all always have an AccountID property no matter what.

This is some non-working code to hopefully give you the gist of what I'm trying to accomplish...

public void CheckForAccountAuthorization<T>(IQueryable<T> entityWithAccountIdProperty)
{
    IEnumerable<string> accountIdList 
        = entityWithAccountIdProperty.Select(u => u.AccountID).Distinct();

    //Do More Work...

    }
}

But it gives me the errors:

Unknown method 'Select(?)' of 'System.Linq.IQueryable'

Unknown member 'AccountID' of 'T'

like image 886
RichC Avatar asked Nov 27 '25 06:11

RichC


1 Answers

Create some interface with AccountID property:

public interface IAccount
{
    int AccountID { get; set; }
}

And make User entity, Transaction entity, and Product entity implement it:

public class User : IAccount
{
    public int AccountID { get; set; }
    // ... 
}

Then make constraint on generic type parameter:

public void CheckForAccountAuthorization<T>(IQueryable<T> accounts)
   where T : IAccount
{
    IEnumerable<string> accountIdList 
        = accounts.Select(u => u.AccountID).Distinct();

    // ...
}

Now you have AccountID property available.

like image 145
Sergey Berezovskiy Avatar answered Nov 29 '25 20:11

Sergey Berezovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!