Loading property after object has been attached

ef-code-first, entity-framework-4

Solution

Your first case doesn't work because your entity is not wrapped by dynamic proxy and navigation property cannot be lazy loaded. Try this:

var context = new MyContext();
var newObj = context.Apontamentos.Create();
newObj.Filial = "01",
nowObj.OperacaoCodigo = "001"

context.Apontamentos.Attach(newObj);
var desc = newObj.Operacao.Descricao;

You can also continue using your current solution and load property explicitly:

 var context = new MyContext();
 var newObj = new Apontamento
     {
         Filial = "01",
         OperacaoCodigo = "001"
     };
 context.Apontamentos.Attach(newObj);
 context.Entry(newObj).Reference(o => o.Operacao).Load();
 var desc = newObj.Operacao.Descricao;

Problem

I´ve tried to google it before asking here and I couldn´t find any solution. I have these two classes and a single mapping one-to-many I´m 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. } } ```

Original source