2

If I want single primitive value like int, string, float etc I can do like this.

using (var db = new SQLiteConnection(DbPath))
{
    double i = db.CreateCommand("select salary from PersonMaster where personId = ?", 9).ExecuteScalar<double>();
}

If I try to return whole object of person master i.e. single row the below code returns null

using (var db = new SQLiteConnection(DbPath))
{
    PersonMaster objPersonMaster = db.CreateCommand("select * from PersonMaster where personId = ?", 9).ExecuteScalar<PersonMaster>();
}

I compulsory have to use this

using (var db = new SQLiteConnection(DbPath))
{
    List<PersonMaster> lstPersonMaster = db.Query<PersonMaster>("select * from PersonMaster where personId = ?", 9);
    PersonMaster objPersonMaster = lstPersonMaster.First();
}

Is there any way to get single row as object, rather than dealing with List<T>

3 Answers 3

2

I am assuming you are using SQLite-Net. If that is the case you can use the Find method. Find gets an object using its primary key.

The personId field needs the PrimaryKey attribute as follows:

public class PersonMaster
{
    [PrimaryKey]
    public int personId { get; set; }

    public string name { get; set; }
    public decimal salary { get; set; }
}

Then you can use Find like so:

// get person 9
PersonMaster person9 = db.Find<PersonMaster>(9);
Sign up to request clarification or add additional context in comments.

3 Comments

What to do if I have no primary key in the table ? If my whe, then how can I do that ?
@Xyroid - If you don't have a key, then you have to use First
@Xyroid: Find() can also take a predicate: db.Find<PersonMaster>(person => person.name == "Xyroid")
1

You can either use "TOP(1) yourquery" or "yourquery LIMIT 1"

Comments

0

if you just want to get rid of the list step, you can do it directly:

PersonMaster objPersonMaster = db.Query<PersonMaster>("select * from PersonMaster where personId = ?", 9).First();

Of course you have to deal with a possible exception in case nothing is returned, but you should do this also with the list approach anyway.

1 Comment

That I know, but I don't want to go in List<T> way.

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.