Hi, I am trying to create a dynamic query for certain funtions. I have a base entity with some common fields to all of derived my entities. I want to create a function to retrieve an entity based by the ID but I will like to write generic function to do this.. Below is the code I will like to use. [HierarchyRoot] public class MyEntity : Entity { [Field, Key] public int Id { get; private set; }
public class Folder : MyEntity {
The function generic function I would like to have is function Entity GetEntityByID<t>(int id) { Folder folder = (from f in Session.Query.All<t>() where f.Id == id select f).FirstOrDefault<t>(); return folder; } I know the Query.All() takes a type and not generic type. Is there any other way I can accomplish these types of generic functions. Thank you, Richard |
Hello Richard, you can accomplish that using generic parameter constraints. For example:
It's also worth mentioning that DataObjects.Net provides standard way to fetch entity by its key fields
Despite this looks similar to LINQ query, this method uses our internal query pipeline directly. Also it first looks in session cache, so if your entity is already loaded, it will not access the database at all. |
Denis, That worked!... Thanks very much for your prompt response. Richard |