質問

I have domain model Task in domain layer and persistence model eTask in infrastructure:

class Task : IAggregateRoot, EntityBase
{
    private string taskText;

    public Task(string taskText)
        :this(null, taskText)
    {          
    }

    public Task(object id, string taskText)
        :base(id)
    {
        //argument validation
        this.taskText = taskText;
    }

    //some business logic here
}

...

class eTask
{
    public Guid ID { get; set; }
    public string TaskText { get; set; }
}

I have repository interface ITaskRepository and its implementation that uses EF with persistence model eTask and maps eTask to Task when returning result items

interface ITaskRepository : IRepository<Task>
{
    IEnumerable<Task> GetTasksBySpecification(ISpecification<Task> spec);
}

The ISpecification interface is like:

interface ISpecification<T>
{
    Expression<Func<T, bool>> IsSatisfiedBy();
}

The problem is in ITaskRepository.GetTasksBySpecification implementation. I try to find out how to convert specification object spec to expression for Entity framework's entities eTask. How can I do that?

役に立ちましたか?

解決

If you want o use expressions, then you have to write your very own expression parser which will generate the relevant linq2sql expressions.

A much easier way is to use simple objects, dedicated for the specific criteria

public class TaskSelectionCriteria
{
      public Guid? Id {get;set;}
      public string TaskText {get;set;}
}

Then in the repo you can check if Id is not null, add Where(d=>d.Id=criteria.Id.Value) , if has a TaskTExt, add the corresponding EF condition and so on.

It's not that cool as using expressions, but it's MUCH easier to implement and maintain. And you keep the EF stuff unknown to the rest of the app.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top