在附加对象后加载属性

时间:2012-04-19 20:32:15

标签: entity-framework-4 ef-code-first

我在尝试之前试图谷歌,我找不到任何解决方案。

我有这两个类和一对一的映射

我正在尝试附加一个新对象

    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.

        }
    }

1 个答案:

答案 0 :(得分:6)

您的第一个案例不起作用,因为您的实体未被动态代理包装,导航属性无法延迟加载。试试这个:

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

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

您还可以继续明确地使用当前解决方案和加载属性:

 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;