Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to generic instance property

How can I access to the Id property of the instance? I have the following code:

public void InsertOrUpdate(Book book)
{
    if (book.Id == default(int)) {

And I want to make it generic now:

public class TheRepository<T> : IRepository<T> where T : class
{
    public void InsertOrUpdate(T instance)
    {
        if (instance.Id == default(int))//How can I access Id here
        {
            context.Set<T>().Add(instance);

I searched for similar posts and I think I should write something like instance.GetType().GetProperty("Id").GetValue() but I don't know how exactly?


1 Answers

You could do a hack like this. Define an interface with only one property of type int called Id:

interface IHaveId
{
    public int Id { get; set; }
}

Then state that you entity implements the interface:

public class Book : IHaveId

Last state that the type used in your generic Repository class should implement this interface.

public class TheRepository<T> : IRepository<T> where T : class, IHaveId
{
    public void InsertOrUpdate(T instance)
    {
        if (instance.Id == default(int))
        {
            context.Set<T>().Add(instance);
        }
    }
}

Doing so you avoid the use of reflection, which is very expensive in general terms. Furthermore, your code now is more clear.

like image 144
Christos Avatar answered Mar 25 '26 23:03

Christos



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!