C# 有没有一种方法可以在LINQDataContext中实现Select条件

C# 有没有一种方法可以在LINQDataContext中实现Select条件,c#,asp.net-mvc,linq-to-sql,C#,Asp.net Mvc,Linq To Sql,我在一个MVC3项目中工作,我正在使用LINQtoSQL。我有一个数据库模式,它使用一个字段来指示记录是活动的还是已删除的(字段是名为“活动”的布尔值)。 现在假设有两个链接的表,例如State和City,其中City引用State。 假设我有一个返回状态列表的方法: public ActionResult ListStates() { return View(_repository.ListStates()); } 现在,我已经实现了repository方法来返回所有状态,我可以通过以

我在一个MVC3项目中工作,我正在使用LINQtoSQL。我有一个数据库模式,它使用一个字段来指示记录是活动的还是已删除的(字段是名为“活动”的布尔值)。 现在假设有两个链接的表,例如State和City,其中City引用State。 假设我有一个返回状态列表的方法:

public ActionResult ListStates()
{
   return View(_repository.ListStates());
}
现在,我已经实现了repository方法来返回所有状态,我可以通过以下方式实现它:

public class Repository
{
   public IQueryable<State> ListStates()
   {
      return dataContext.States.Where(p => p.Active == true)
   }
}
每当插入State对象时,就会执行上述方法。
我的问题是,是否有一种方法可以只在一个位置为对象实现一个条件,例如在执行选择时只返回活动记录?

您正在寻找动态linq库:


我以前曾使用此方法在所有select语句中插入一个
,其中IsActive=true

您正在查找动态linq库:


我以前使用过这个方法在所有select语句中插入一个
Where IsActive=true

如果我理解正确,您试图消除在存储库的方法上指定的需要。Where(p=>p.Active==true),您只想定义一次

我不确定是否可以在不创建数据上下文包装器的情况下实现这一点,因为对于每个查询,必须组合两个逻辑表达式,一个来自存储库的表达式和p=>p.Active==true

最简单的解决方案如下:

/// <summary>
/// A generic class that provides CRUD operations againts a certain database
/// </summary>
/// <typeparam name="Context">The Database context</typeparam>
/// <typeparam name="T">The table object</typeparam>
public class DataContextWrapper<Context> where Context : DataContext, new()
{
    Context DataContext;


    /// <summary>
    /// The name of the connection string variable in web.config
    /// </summary>
    string ConnectionString
    {
        get
        {
            return "Connection String";
        }
    }

    /// <summary>
    /// Class constructor that instantiates a new DataContext object and associates the connection string
    /// </summary>
    public DataContextWrapper()
    {
        DataContext = new Context();
        DataContext.Connection.ConnectionString = ConnectionString;
    }


    protected IEnumerable<T> GetItems<T>([Optional] Expression<Func<T, bool>> query) where T : class, new()
    {
        //get the entity type
        Type entity = typeof(T);
        //get all properties
        PropertyInfo[] properties = entity.GetProperties();

        Expression<Func<T, bool>> isRowActive = null;
        //we are interested in entities that have Active property ==> to distinguish active rows
        PropertyInfo property = entity.GetProperties().Where(prop => prop.Name == "Active").SingleOrDefault();

        //if the entity has the property
        if (property != null)
        {
            //Create a ParameterExpression from
            //if the query is specified then we need to use a single ParameterExpression for the whole final expression
            ParameterExpression para = (query == null) ? Expression.Parameter(entity, property.Name) : query.Parameters[0];

            var len = Expression.PropertyOrField(para, property.Name);
            var body = Expression.Equal(len, Expression.Constant(true));
            isRowActive = Expression.Lambda<Func<T, bool>>(body, para);
        }

        if (query != null)
        {
            //combine two expressions
            var combined = Expression.AndAlso(isRowActive.Body, query.Body);
            var lambda = Expression.Lambda<Func<T, bool>>(combined, query.Parameters[0]);
            return DataContext.GetTable<T>().Where(lambda);
        }
        else if (isRowActive != null)
        {
            return DataContext.GetTable<T>().Where(isRowActive);
        }
        else
        {
            return DataContext.GetTable<T>();
        }

    }

}


希望这有帮助;)

如果我理解正确,您正试图消除在存储库的方法上指定.Where(p=>p.Active==true)的需要,并且您只想定义一次

我不确定是否可以在不创建数据上下文包装器的情况下实现这一点,因为对于每个查询,必须组合两个逻辑表达式,一个来自存储库的表达式和p=>p.Active==true

最简单的解决方案如下:

/// <summary>
/// A generic class that provides CRUD operations againts a certain database
/// </summary>
/// <typeparam name="Context">The Database context</typeparam>
/// <typeparam name="T">The table object</typeparam>
public class DataContextWrapper<Context> where Context : DataContext, new()
{
    Context DataContext;


    /// <summary>
    /// The name of the connection string variable in web.config
    /// </summary>
    string ConnectionString
    {
        get
        {
            return "Connection String";
        }
    }

    /// <summary>
    /// Class constructor that instantiates a new DataContext object and associates the connection string
    /// </summary>
    public DataContextWrapper()
    {
        DataContext = new Context();
        DataContext.Connection.ConnectionString = ConnectionString;
    }


    protected IEnumerable<T> GetItems<T>([Optional] Expression<Func<T, bool>> query) where T : class, new()
    {
        //get the entity type
        Type entity = typeof(T);
        //get all properties
        PropertyInfo[] properties = entity.GetProperties();

        Expression<Func<T, bool>> isRowActive = null;
        //we are interested in entities that have Active property ==> to distinguish active rows
        PropertyInfo property = entity.GetProperties().Where(prop => prop.Name == "Active").SingleOrDefault();

        //if the entity has the property
        if (property != null)
        {
            //Create a ParameterExpression from
            //if the query is specified then we need to use a single ParameterExpression for the whole final expression
            ParameterExpression para = (query == null) ? Expression.Parameter(entity, property.Name) : query.Parameters[0];

            var len = Expression.PropertyOrField(para, property.Name);
            var body = Expression.Equal(len, Expression.Constant(true));
            isRowActive = Expression.Lambda<Func<T, bool>>(body, para);
        }

        if (query != null)
        {
            //combine two expressions
            var combined = Expression.AndAlso(isRowActive.Body, query.Body);
            var lambda = Expression.Lambda<Func<T, bool>>(combined, query.Parameters[0]);
            return DataContext.GetTable<T>().Where(lambda);
        }
        else if (isRowActive != null)
        {
            return DataContext.GetTable<T>().Where(isRowActive);
        }
        else
        {
            return DataContext.GetTable<T>();
        }

    }

}


希望这有帮助;)

记住Ctrl+K是键:drember Ctrl+K是键:DNo,我不是在寻找动态查询,我是在寻找一种方法来覆盖/实现数据上下文中对象的默认选择行为。不,我不是在寻找动态查询,我正在寻找一种方法来覆盖/实现数据上下文中对象的默认选择行为。虽然您的解决方案很好,但它仍然不是我要寻找的。尽管您的解决方案很好,但它仍然不是我要寻找的。
/// <summary>
/// States Repository
/// </summary>
public class StatesRepository : DataContextWrapper<DEMODataContext>
{
    /// <summary>
    /// Get all active states
    /// </summary>
    /// <returns>All active states</returns>
    public IEnumerable<State> GetStates()
    {
        return base.GetItems<State>();
    }

    /// <summary>
    /// Get all active states
    /// </summary>
    /// <param name="pattern">State pattern</param>
    /// <returns>All active states tha contain the given pattern</returns>
    public IEnumerable<State> GetStates(string pattern)
    {
        return base.GetItems<State>(s=>s.Description.Contains(pattern));
    }

}
StatesRepository repo = new StatesRepository();
var activeStates = repo.GetStates();
var filtered = repo.GetStates("Al");