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; }

    [Field(Length = 100)]
    public string Name { get; set; }

    [Field(Length = 100)]
    public string Text { get; set; }

    [Field]
    public bool Active {get; set;}

    [Field]
    public DateTime LastModified { get; set; }

    public MyEntity(): base()
    {

    }

public class Folder : MyEntity {

    [Field]
    public int FileCount { get; set; }

    [Field]
    [Association(PairTo = "ParentFolder")]
    public File_EntitySet Files { get; private set; }

    public Folder() : base()
    {

    }

    public Folder(Session session) : base(session)
    {

    }

}

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

asked Jul 17 '13 at 13:42

rasxte's gravatar image

rasxte
20161617


2 Answers:

Hello Richard,

you can accomplish that using generic parameter constraints.

For example:

public T GetEntityByID<T>(int id) where T : MyEntity {
  return (from f in Session.Query.All<T>() where f.Id == id select f).FirstOrDefault();
}

It's also worth mentioning that DataObjects.Net provides standard way to fetch entity by its key fields

Session.Query.SingleOrDefault<T>(id);

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.

answered Jul 17 '13 at 14:37

Denis%20Krjuchkov's gravatar image

Denis Krjuchkov
179325

Denis,

That worked!...

Thanks very much for your prompt response.

Richard

answered Jul 17 '13 at 23:10

rasxte's gravatar image

rasxte
20161617

edited Jul 17 '13 at 23:10

Your answer
Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!
toggle preview

powered by OSQA