Search code examples
c#sqlitesqlite-net

How to add userId to every query without adding it to all domain classes?


I'm working with sqlite and the c# sqlite-net library. Some of my entities:

public class Product
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [MaxLength(50)]
    public string Name { get; set; }
    [MaxLength(50)]
    public string Brand { get; set; }
    [MaxLength(50)]
    public string Type { get; set; }
    [MaxLength(50)]
}

public class ProductImage
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Container { get; set; }
    public int ProductId { get; set; }
}

Now all entities belong to a user and the user should always work only with his own entities. So when I insert an entity in the database I want to store the userId with it. However... I don't want to add the userId to all my domain classes.

I'm storing my entities like this right now:

  • await _databaseManager.GetDatabaseInstance().InsertAsync(entity);

and selecting like this:

  • var products = await _databaseManager.GetDatabaseInstance().Table().ToListAsync();

So is there a way with sqlite-net to add the userId to the database without adding it to all domain classes?


Solution

  • Doesn't it support inheritance, as in looking at the type's hierarchy? I would suggest it would, or at least should. So, if it does you could use an abstract base class or an interface. Something like this:

    public abstract class StandardEntity {
      public int UserId { get; set; } // decorate with attributes as necessary
    }
    

    And inherit:

    public class Product : StandardEntity {
    
    }