wil*_*ill 4 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.
}
}
您的第一个案例不起作用,因为您的实体未被动态代理包装,并且导航属性无法延迟加载.试试这个:
var context = new MyContext();
var newObj = context.Apontamentos.Create();
newObj.Filial = "01",
nowObj.OperacaoCodigo = "001"
context.Apontamentos.Attach(newObj);
var desc = newObj.Operacao.Descricao;
Run Code Online (Sandbox Code Playgroud)
您还可以显式继续使用当前解决方案和加载属性:
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1300 次 |
| 最近记录: |