简体   繁体   English

LINQ where未知类型的表达

[英]LINQ Where expression of unknown type

I have a database where all tables have a primary key named ID . 我有一个数据库,其中所有表都有一个名为ID的主键。

I don't want to have to make multiple GetObjectForId for all my tables, i would like to make a generic method that takes IQueryable and a Type and then try to get an object from the IQueryable selection if possible. 我不想为我的所有表制作多个GetObjectForId,我想制作一个采用IQueryable和Type的通用方法,然后尽可能尝试从IQueryable选择中获取一个对象。

I'm thinking something like this: 我在想这样的事情:

public IQueryable<Type> GetObjectForIdInCollection(IQueryable selection, Type t, int id)
{
    return selection.Cast<T>().Where(c => c.ID == id).FirstOrDefault()
} 

Obviously this code is totally wrong, but you get the idea what i'm trying to do. 显然,这段代码是完全错误的,但是您知道我正在尝试执行的操作。

Is this a good idea? 这是一个好主意吗? How can i implement this method? 我该如何实现这种方法?

If you are using Code-First, then you can create BaseEntity class and derive all entities from this class. 如果使用的是Code-First,则可以创建BaseEntity类并从该类派生所有实体。

public abstract class BaseEntity
{
    public int ID { get; set; }
}

Then, 然后,

public T GetObjectForIdInCollection<T>(IQueryable<T> selection, int id)
    where T : BaseEntity
{
    return selection.Where(c => c.ID == id).FirstOrDefault();

    // Or you can simply use:
    // return selection.FirstOrDefault(c => c.ID == id);
} 

you could create a base interface, which all your entities implement: 您可以创建一个基本接口,您的所有实体都可以实现:

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

// ...

public T GetObjectForIdInCollection<T>(IQueryable<T> selection, int id)
    where T : IIdObject
{
    return selection.FirstOrDefault(c => c.Id == id);
}  

but I don't think it is worth the effort. 但我认为这样做不值得。

Your classes should implement IEntity interface, also you can use extension method: 您的类应实现IEntity接口,也可以使用扩展方法:

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

public static class Extention
{
    public static Type GetObjectForIdInCollection<Type>(this IQueryable<Type> selection, int id)
         where Type : class, IEntity
    {
        return selection.FirstOrDefault(c => c.Id == id);
    }
}

Usage: 用法:

var item = source.GetObjectForIdInCollection(1);

I think you must inherit all your models from a base class (the base type BaseModel) that has ID as property, then : 我认为您必须从具有ID作为属性的基类(基类型BaseModel)继承所有模型,然后:

public GetById<T>(int id, IRepository repo) where T : BaseModel
        {

                IQueryable<T> setQuery = repo.Get<T>();
                return setQuery.FirstOrDefault(q => q.Id== id);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM