C# Entity Dbset with DDD?

Asked

Viewed 142 times

0

I have an app C# MVC with DDD and in the repository I’m making the call like this:

 return DbSet.Include(i => i.Cliente).FirstOrDefault(a => a.ProcessoId == processoId);

DbSet-> is in the repositoy process

public class Processo
{
    public int Id { get; set; }
    public string Obs { get; set; }  <- varchar(max)
    public int? ClienteId { get; set; }
    public virtual Cliente Cliente { get; set; }
}

Doubts:

Using the DbSet it is possible to ignore the field Obs, on the return of the consultation?

(or rather than do SELECT * seja feito SELECT Id, ClienteId, ... Join...)

Does anyone know any other way to do this and keep the include?

Any component, similar design, suggestions will be welcome.

1 answer

0

I was in doubt in some fields, but, can be done the Include, after a Select and finally the filter inside the FirstOrDefault:

var result = DbSet
      .Include(i = i.Cliente)
      .Select(s => new {
          s.Id, 
          s.ClienteId,
          s.Cliente
      })
      .FirstOrDefault(i => i.Id == processoId); 

in that case I specify the variable result is an anonymous guy (desconhecido). If you want to return a specific type (Strongly Typed), create a classe that represents this result, example:

public class ProcessoViewModel
{
    public int Id {get;set;}
    public int? ClienteId {get;set;}
    public Cliente Cliente {get;set;
}

Make the change in the code:

ProcessoViewModel result = DbSet
      .Include(i = i.Cliente)
      .Select(s => new ProcessoViewModel
      {
          Id = s.Id, 
          ClienteId = s.ClienteId,
          Cliente = s.Cliente
      })
      .FirstOrDefault(i => i.Id == processoId);

Some reply who can help you:

  • but it will return Generic object, to return Process must have a new Process{}

  • @Marcoviniciussoaresdalalba is true it will generate an anonymous type, not generic, a type created at runtime, since the user wants to disregard a field of his class.

  • The above solution is good for small objects. When I have a very large object it becomes difficult to maintain, even when adding new properties (when working in a group that is my case), so I’m thinking the opposite, inform the fields I do not want to click on my return object whether this is generic or not.

  • @nfrigo so it was added two possible ways. Depending on the case choose one of them ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.