Best way of constructing dynamic sql queries in C#/.NET3.5?

后端 未结 12 2831
走了就别回头了
走了就别回头了 2021-02-15 11:25

A project I\'m working on at the moment involves refactoring a C# Com Object which serves as a database access layer to some Sql 2005 databases.

The author of the existe

12条回答
  •  独厮守ぢ
    2021-02-15 11:31

    This is the way I'd do it:

    public IQueryable GetClients(Expression> criteria)
        {
            return (
                from model in Context.Client.AsExpandable()
                where criteria.Invoke(model)
                select new Ibfx.AppServer.Imsdb.Entities.Client.ClientEntity()
                {
                    Id = model.Id,
                    ClientNumber = model.ClientNumber,
                    NameFirst = model.NameFirst,
                    //more propertie here
    
                }
            );
        }
    

    The Expression parameter you pass in will be the dynamic query you'll build with the different WHERE clauses, JOINS, etc. This Expression will get Invoked at run time and give you what you need.

    Here's a sample of how to call it:

    public IQueryable GetClientsWithWebAccountId(int webAccountId)
        {
            var criteria = PredicateBuilder.True();
            criteria = criteria.And(c => c.ClientWebAccount.WebAccountId.Equals(webAccountId));
            return GetClients(criteria);
        }
    

提交回复
热议问题