I tried this before asking here, and I did not find any solution.
I have these two classes and one one-to-many mapping
I am trying to attach a new object
public class MyContext: DbContext
{
public IDbSet Operacoes {get; set; }
public IDbSet Apontamentos {get; set; }
}
public class Operacao
{
public string Filial {get; set; }
public string Codigo {get; set; }
public string Descricao {get; set; }
}
public class apontamento
{
public int Id {get; set; }
public string Filial {get; set; }
public string OperacaoCodigo {get; set; }
public virtual Operacao Operacao {get; set; }
}
public class OperacaoMap: EntityTypeConfiguration
{
public OperacaoMap ()
{
ToTable ("za6010");
HasKey (x => new {x.Filial, x.Codigo})
.Property (x => x.Codigo) .HasColumnName ("za6_cod");
Property (x => x.Descricao) .HasColumnName ("za6_desc");
}
}
public class ApontamentoMap: EntityTypeConfiguration
{
public ApontamentoMap ()
{
ToTable ("za4010");
HasKey (x => new {x.Filial, x.Id});
Property (x => x.OperacaoCodigo)
.HasColumnName ("za4_oper");
//
HasRequired (x => x.Operacao)
.WithMany ()
.HasForeignKey (x => new {x.Filial, x.OperacaoCodigo})
.WillCascadeOnDelete (false);
}
}
public static class Program
{
static void main ()
{
// this not work, and I need it to work.
var context = new MyContext ();
var newObj = new Apontamento
{
Filial = "01",
OperacaoCodigo = "001"
};
context.Apontamentos.Attach (newObj);
var desc = newObj.Operacao.Descricao; // Here Operacao Property is null
// this works
var newObjTmp = new Apontamento
{
Filial = "01",
OperacaoCodigo = "001"
};
var operacao = context.Operacoes.Where (x => x.Codigo == "001");
context.Apontamentos.Attach (newObj);
var descTmp = newObjTmp.Operacao.Descricao; // Operacao Property is ok.
}
}
source
share