1

如果我有一个由数据库中的表表示的类

public class Foo
{
    public string Bar1 {get; set;}
    public string Bar2 {get; set;}
}

class DataContext : DbContext
{
    public DbSet<Foo> Foos { get; set; }
}

public enum FooDataStatus {Bar1Missing, Bar2Missing, Bar1And2Missing, Complete}

public class MappedFoo
 {
    public string Bar1 {get; set;}
    public string Bar2 {get; set;}
    public FooDataStatus DataStatus ... property or method ...
}

我希望能够重用逻辑来为 MappedFoo 的单个实例以及 iqueryables 返回 FooDataStatus,这样我就可以计算数据库中具有每个 FooDataStatus 的记录数,而无需传递数据库中的所有记录。

int completedRecords = (From f in DataContext.Foos
                        ....magic goes here ...
                        ).Count(d=>d==FooDataStatus.Complete);

请注意,这是我所追求的简化版本,但所有逻辑都可以轻松映射 sql 等效运算符,但足够复杂,重复逻辑似乎并不明智。

(From f in DataContext.Foos
 where f.Bar1!=null && f.Bar1!="" && f.Bar2!=null && f.Bar2 != "").Count();

如何创建更可重用的逻辑集?

4

1 回答 1

0

我最终使用了(并且我希望获得有关如何改进的任何提示,特别是 DataStatus 获取属性访问器)>我很高兴在下面标记为答案改进:

public class Foo : IFoo
{
    public string Bar1 {get; set;}
    public string Bar2 {get; set;}
}

public class MappedFoo : IFoo
{
    public string Bar1 {get; set;}
    public string Bar2 {get; set;}
    public FooDataStatus DataStatus { get { return CalculateRecordStatusOption.Compile()(this);}}
    public static Expression<Func<IFoo, FooDataStatus>> CalculateRecordStatusOption =
        r =>
            (r.Bar1 == null || r.Bar1 == "")
                ? FooDataStatus.Bar1Missing
                :(r.Bar2 == null || r.Bar2 == "")
                    ? FooDataStatus.Bar2Missing
                    : FooDataStatus.NoneMissing;
}

interface IFoo
{
    string Bar1 {get; set;}
    string Bar2 {get; set;}
}

class Program
{
    static void Main()
    {
        using (var context = new DataContext())
        {
            var emptyRecordCount = context.Foos
                .Select(MappedFoo.CalculateRecordStatusOption)
                .Count(f=>f == FooDataStatus.NoneMissing);
于 2013-10-29T22:03:27.243 回答