1

I have a simple data base control handler class.

It uses a SQLiteConnection. I have several tables in my SQLite db.

Now I want to write a generic simple accessor function for all tables of a specific type that use an int Id as primary key. Therefore I have a base class TableWithIntId that always has an int Id as primary key.

My simplified code is:

private SQLiteConnection sqliteConnection;

public T LoadRecord<T>(int id) where T : Database.TableWithIntId
{
    try
    {
        return (from objTable in sqliteConnection.Table<T>()
            where objTable.Id == id
            select objTable).First();
    }
    catch (Exception ex)
    {
        ErrorMessage = ex.Message;
        return null;
    }
}

The problem is, that I get the following error:

error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'SQLiteConnection.Table()'

This is confusing for me, because T is non abstract and has an automatic default constructor.

public class TableWithIntId
{
    [PrimaryKey]
    public int Id { get; set; }
}  
1
  • 1
    You need to specify new() constraint for T in where clause. Commented Dec 18, 2017 at 9:55

2 Answers 2

3

The constraint where T : Database.TableWithIntId only states that T must derive from Database.TableWithIntId. But derived classes don't necessarily have a parameterless constructor (if you give them only constructors with parameters).

Add a new() constraint to solve that:

public T LoadRecord<T>(int id) where T : Database.TableWithIntId, new()

That restricts T to classes with parameterless constructors.

Sign up to request clarification or add additional context in comments.

Comments

1

Take a look at new Constraint (C# Reference)

  public T LoadRecord<T>(int id) where T : TableWithIntId, new()
    {
       try
       {
           return (from objTable in sqliteConnection.Table<T>()
                   where objTable.Id == id
                   select objTable).First();
       }
       catch (Exception ex)
       {
           ErrorMessage = ex.Message;
           return null;
       }
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.