在我的webapi2应用程序中,我使用了第一代数据库,并且创建了部分上下文上下文,将ProxyCreationEnabled
和LazyLoadingEnabled
都设置为false。
但是当我使用db.ExameViaAereaOssea.Where(e => e.ConsultaId == model.ConsultaId).ToList()
时,关系属性Consulta也会被加载。
使用db.ExameViaAereaOssea.AsNoTracking().Where(e => e.ConsultaId == consultaId).ToList()
我不想对每个查询都使用AsNoTracking
这是我的两个班
public partial class ExameViaAereaOssea
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ExameViaAereaOssea()
{
}
public int ExameViaAereaOsseaId { get; set; }
public Nullable<int> ConsultaId { get; set; }
public string VAOE125 { get; set; }
public string VAOE250 { get; set; }
public string VAOE500 { get; set; }
public string VAOE750 { get; set; }
public string VAOE1000 { get; set; }
public string VAOE1500 { get; set; }
public string VAOE2000 { get; set; }
public string VAOE3000 { get; set; }
public string VAOE4000 { get; set; }
public string VAOE6000 { get; set; }
public string VAOE8000 { get; set; }
public string VOOE500 { get; set; }
public string VOOE750 { get; set; }
public string VOOE1000 { get; set; }
public string VOOE2000 { get; set; }
public string VOOE3000 { get; set; }
public string VOOE4000 { get; set; }
public string TipoAudiometria { get; set; }
public virtual Consulta Consulta { get; set; }
}
public partial class Consulta
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Consulta()
{
this.ExameViaAereaOssea = new HashSet<ExameViaAereaOssea>();
}
public int ConsultaId { get; set; }
public DateTime? Data {get;set;}
public Nullable<int> PacienteId { get; set; }
public Nullable<int> TipoConsultaId { get; set; }
public Nullable<int> PacienteDadosProfissionaisId { get; set; }
public Nullable<int> ClienteId { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ExameViaAereaOssea> ExameViaAereaOssea { get; set; }
}
这是用法。
public class RegraConsulta(){
public ExamesConsulta BuscaExamesConsulta(Consulta model) {
using (var db = new winmedEntities(false))
{
var retorno = new ExamesConsulta();
retorno.DataConsulta = RetornaDataConsulta(db, model.ConsultaId);
retorno.exAereaOssea = db.ExameViaAereaOssea.Where(c => c.ConsultaId == model.ConsultaId).ToList();
return retorno;
}
}
public DateTime RetornaDataConsulta(winmedEntities db, int consultaId)
{
var consulta = db.Consulta.Find(consultaId);
if (consulta == null)
throw new RegraNegocioException("Consulta não encontrada");
return consulta.Data.Value;
}
}
返回值用于Web Api控制器,返回方法类似于return Ok(new RegraConsulta().BuscaExamesConsulta(new Consulta { ConsultaId = 1 }));