Combining C# code and database code in a Specification

江枫思渺然 提交于 2019-12-19 03:36:18

问题


Sometimes you need to define some business rules and the Specification pattern is a useful tool. For example:

public class CanBorrowBooksSpec : ISpecification<Customer>
{
    public bool Satisfies(Customer customer)
    {
         return customer.HasLibraryCard
              && !customer.UnpaidFines.Any();
    }
}

However, I often find that I need to 'push' these rules into SQL to improve performance or to cater for things like paged lists of records.

I am then left with having to write code for the rules twice, once in CLR code, and once in SQL (or ORM language).

How do you go about organising code like this?

It seems best if the code was kept together in the same class. That way, if the developer is updating the business rules they have less chance of forgetting to update both sets of code. For example:

public class CanBorrowBooksSpec : ISpecification<Customer>
{
    public bool Satisfies(Customer customer)
    {
         return customer.HasLibraryCard
              && !customer.UnpaidFines.Any();
    }

    public void AddSql(StringBuilder sql)
    {
        sql.Append(@"customer.HasLibraryCard 
                     AND NOT EXISTS (SELECT Id FROM CustomerUnpaidFines WHERE CustomerId = customer.Id)");
    }
}

However this seems quite ugly to me as we are now mixing concerns together.

Another alternative would be using a Linq-To-YourORM solution, as the LINQ code could either be run against a collection, or it could be translated into SQL. But I have found that such solutions are rarely possible in anything but the most trivial scenarios.

What do you do?


回答1:


We used Specification pattern with Entity Framework. Here's how we approached it

public interface ISpecification<TEntity>
{
    Expression<Func<TEntity, bool>> Predicate { get; }
}


public class CanBorrowBooksSpec : ISpecification<Customer>
{
    Expression<Func<Customer, bool>> Predicate 
    { 
       get{ return customer => customer.HasLibraryCard
              && !customer.UnpaidFines.Any()} 
    }
}

Then you can use it against LINQ-to-Entities like

db.Customers.Where(canBorrowBooksSpec.Predicate);

In LINQ-to-Objects like

customerCollection.Where(canBorrowBooksSpec.Predicate.Compile());


来源:https://stackoverflow.com/questions/7200792/combining-c-sharp-code-and-database-code-in-a-specification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!