开发者

c# Linq to SQL and Generics

Im quite new to generics and as a learning exercise Im trying to create a simple method that picks an entity from an entity set (table) with a specified ID.

    public T GetEntity<T>(int id) where T : class
    {
        return db.GetTable<T>().SingleOrDefault(o => o.id == id); 
    }开发者_如何学C

The above obviously wont work because o in o.id is unknown and thus cannot access the property id - can someone help with how to achieve this?


If all of your entities contain an id property then you can define an interface

public interface IEntity
{
    int id { get; }
}

implement it on all your classes and change your method to

public T GetEntity<T>(int id) where T : IEntity
{
    return db.GetTable<T>().SingleOrDefault(o => o.id == id); 
}

Such interface can be useful in all the places where you want to do something for all your entities, ie. Delete by id. You can add more properties to your interface, ie. timestamp.


If you cannot change your entity classes (for implementing a common interface), you could use a predicate function and pass it into the method

public T GetEntity<T>(int id, Func<T, int, bool> predicate) where T : class
{
    return db.GetTable<T>().SingleOrDefault(o => predicate(o,id));
}


Another solution, not recommended for performance reasons, but i shall post it anyway.

public T GetEntity<T>(int id) where T : class 
    { 

        return db.GetTable<T>().AsEnumerable().SingleOrDefault(o => (int)o.GetType().GetProperty("Id").GetValue(o,null) == id);

    } 


You need to set a constrain on your T so the compiler can be sure there is a id property. Once way is to use interfaces, ie.

public interface IUnique 
{
   int id { get; set; }
}

Then you can say

public T GetEntity<T>(int id) where T : class, IUnique
{
    return db.GetTable<T>().SingleOrDefault(o => o.id == id); 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜