Pergunta

I recently started working with ServiceStack and its ORMLite framework. I have searched on Google and browsed the source code but couldn't find anything relevent.

Is there any way to select specific columns when executing a query with ORMLite ? Something like that : Db.First<Model>(q => q.Id == someId, "Column1, Column2")

Unless I missed this feature, I am surprised nobody asked about this before, since this is one the rule of thumbs to optimize your DB transactions.

Foi útil?

Solução

If you want to specify columns other that the table you need to use SQL as seen in this earlier example

So in your case you could do something like:

Db.First<Model>("SELECT Column1, Column2 FROM AnyTableOrView");

You can also create a partial model that looks at your table by decorating it with the [Alias] attribute, like:

[Alias("AnyTableOrView")]
public class Model {
    public int Id { get; set; }
    public string Column1 { get; set; }
    public string Column2 { get; set; }
}

Then you can do something like:

Db.First<Model>(q => q.Id == someId);

And it will only SELECT + populate fields from the partial model.

Outras dicas

I did try this :

  1. Created a Database VIEW (table name and columns are already set)
  2. Created a class named "Event" and matching each fields for that table with a property (i used [Alias] for table name and for all columns to have nice names)
  3. Wrote access to DB to select 1 record based on it's ID

        var dbFactory = new OrmLiteConnectionFactory(
            "Data Source=MyDB;User Id=user;Password=pwd",  // Connection String
            OracleDialect.Provider);
    
        using (var db = dbFactory.OpenDbConnection())
        {
                var event = db.GetByIdOrDefault<Event>( request.Id );
        }
    

At that point the var 'event' is populated but only the Id field is filled ! all the others fields of the class are not filled (while there are really data in database).

It's the simplest i can do and it does not work. Any ideas ? (PS : i am using OrmLite for Oracle)

Thanks

I have found the problem. It was due to an incorrect type matching between field in my class (defined as a string) and the corresponding Oracle Field (that is a DATE).

I replaced the string with datetime and worked like a charm.

So it's working perfectly with a VIEW and that's GREATLY simplify the code.

I had a similar problem, however my solution was different.

I had a int property in my POCO. My query (from Oracle) was returning a null for this property. It caused a exception to be raised and prevented further processing of that row. The result was a partial populated POCO.

The solution was to change to type to be nullable.

public int? mypropperty
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top