C# anonymous object property inside a generic method after casting

103 Views Asked by At

CS1061 'object' does not contain a definition for 'Id'

public static async Task RemoveItem<T>(object obj) where T : class, new()
{
    if (obj == null || db == null)
        return;

    obj = obj as T;

    await db.DeleteAsync<T>(obj.Id); // error
}

Is this possible to solve or have I reached the edge?

1

There are 1 best solutions below

11
user3772108 On

IMPORTANT: That question is marked duplicate and already closed. Nevertheless I want to share my original solution and than the result thanks to the comments.

While typing I've found the solution out :-) Thanks to Test if a property is available on a dynamic variable

public static async Task RemoveItem<T>(object obj) where T : class, new()
{
    if (obj == null || db == null)
        return;

    dynamic objA = obj as T;

    try
    {
        int id = objA.Id; // Check if property exists
        await db.DeleteAsync<T>(id);
    }
    catch (Exception)
    {
        throw;
    }
}

EDIT after comments:

public static async Task RemoveItem<T>(object obj) where T : class, IDatabaseEntity, new()
{
    if (obj == null || db == null)
        return;

    var entity = obj as IDatabaseEntity;
    await db.DeleteAsync<T>(entity.Id);
}