modeling 0..1 to 1 in the Entity Framework - Error The entity or complex

0

I'm trying to make a linq query, but it returns the error:

  

Additional information: The entity or complex type   'WMB.Celielo.Model.CieloToken' can not be constructed in a LINQ to   Entities query.

My query:

    var temp = (from tok in db.CieloTokens
             join rec in db.CieloRecorrencias
             on tok.CieloRecorrenciaId equals rec.CieloRecorrenciaId 
             where rec.ClienteId == IDC && tok.ClienteId == IDC && tok.CieloRecorrenciaId > 0
             select new CieloToken()).FirstOrDefault();

My 2 models (I removed some properties / attributes to decrease the post):

  public class CieloToken
    {
        [Key, ForeignKey("CieloRecorrencia")]
        [Column("int_ID")]
        public int CieloTokenId { get; set; }

        [Column("int_IDC")]
        public int ClienteId { get; set; }

        [Column("str_Token")]
        [MaxLength(100)]
        public string Token { get; set; }

        public int? CieloRecorrenciaId { get; set; }

        public virtual CieloRecorrencia CieloRecorrencia { get; set; }

    }

public class CieloRecorrencia
{
    [Key]
    [Column("int_ID")]
    public int CieloRecorrenciaId { get; set; }

    public int ClienteId { get; set; }
    public virtual CieloToken cieloToken { get; set; }
}

I tried to do with LAMBDA

    var teste_Capeta = db.CieloTokens
            .Include(i => i.CieloRecorrencia)
            .FirstOrDefault(w => w.ClienteId == IDC && w.CieloRecorrencia.ClienteId == IDC && w.CieloRecorrenciaId > 0);

Then the value is null , where there are records.

    
asked by anonymous 05.04.2016 / 18:40

1 answer

2

Your problem is when you make a select new CieloToken() .

Try this:

var temp = (from tok in db.CieloTokens
             join rec in db.CieloRecorrencias
             on tok.CieloRecorrenciaId equals rec.CieloRecorrenciaId 
             where rec.ClienteId == IDC && tok.ClienteId == IDC && tok.CieloRecorrenciaId > 0
             select tok).FirstOrDefault();

So you will return the record that the database query returns. If you need join information you can create an anonymous object.

The where rec.ClienteId == IDC && tok.ClienteId == IDC line may be the reason you do not get results. You do not need public int? CieloRecorrenciaId { get; set; } property, relationship mapping is already done in class CieloRecorrencia

    
05.04.2016 / 18:52