Denis Debacker Denis Debacker - 2 months ago 14
SQL Question

Linq query & generics

I have about 3 classes,

Author
,
Book
&
Library
. I have the following function which makes use of generics to query the DB for all records:

public static System.ComponentModel.BindingList<T> getRecordsOfType<T>() where T : class, IEntity
{
var records = session.Query.All<T>();
return new System.ComponentModel.BindingList<T>(records.ToList<T>());
}


This works fine, now my following function should get one record using its Id:

public static System.ComponentModel.BindingList<T> getRecordOfTypeById<T>(int intId) where T : class, IEntity
{
var record = session.Query.All<T>().Where(p => p.Id == intId);
return new System.ComponentModel.BindingList<T>(record.ToList<T>());
}


Here C# doesn't know that p will have the property Id (which all my classes have that will be using this function) because I'm using generics.

Of course I could iterate through Library, Book and Author and write a different query for each, but if I want to expand I'll have write extra code in this function.

Can this be solved using Linq, or will I need to work around this?

Answer

IEntity should contain property called Id and it will work, or you can make other interface IHaveId for e.g.

public static System.ComponentModel.BindingList<T> 
              getRecordOfTypeById<T>(int intId) where T : class, IEntity, IHaveId

and interface like:

public interface IHaveId
{
    int Id { get; set;}
}

All of entities used in this method should implement IHaveId interface

If you do all above you will be sure that p will have Id and you will be able to use it in generic method.

Comments