Here are my two objects
public class ObjectHeaderBuffer
{
public int DataObjectId { get; set; }
public string FileName { get; set; }
public int RowCount { get; set; }
public string Checksum { get; set; }
public int ReconTarget { get; set; }
}
public class ObjectHeaderAttribute
{
public int DataObjectId { get; set; }
public int AttributeType { get; set; }
public int AttributeValue { get; set; }
}
var ohBuffer = new List<ObjectHeaderBuffer>();
var ohAttribute = new List<ObjectHeaderAttribute>();
I want to update ohBuffer.ReconTarget with ohAttribute.AttributeValue where ohBuffer.DataObjectId == ohAttribute.DataObjectId
what is linq or lambda of this?
You need to iterate each item in ohBuffer and look up the value in ohAttribute.
Assuming there is only one Attribute for each Buffer, this will work.
ohBuffer.ForEach(b => b.ReconTarget = ohAttribute
.SingleOrDefault(a => a.DataObjectId == b.DataObjectId).AttributeValue);
If the lookup returns null, you can either coalesce to a new object and take the default value
ohBuffer.ForEach(b => b.ReconTarget =
(ohAttribute.SingleOrDefault(a => a.DataObjectId == b.DataObjectId)
?? new ObjectHeaderAttribute())
.AttributeValue);
or you could just take null
ohBuffer.ForEach(b => b.ReconTarget =
{
var attribute = ohAttribute
.SingleOrDefault(a => a.DataObjectId == b.DataObjectId);
if (attribute == null)
return null;
return attribute.AttributeValue;
});
They way i did is:
foreach (var objectHeaderBuffer in ohBuffer)
{
var objectHeaderAttribute = (from c in ohAttribute where c.DataObjectId == objectHeaderBuffer.DataObjectId select c).First();
objectHeaderBuffer.ReconTarget = objectHeaderAttribute.AttributeValue;
}
If your relation is 1:1 Then
foreach (ObjectHeaderBuffer Itemx in ohBuffer)
{
ObjectHeaderAttribute Itemy= (from ObjectHeaderAttribute c in ohAttribute where c.DataObjectId == Itemx.DataObjectId select c).FirstOrDefault();
if(Itemy!=null)
{
Itemx .ReconTarget = Itemy.AttributeValue;
}
}
Or
foreach (ObjectHeaderBuffer Itemx in ohBuffer)
{
ObjectHeaderAttribute Itemy= ohAttribute.Where(c=>c.DataObjectId == Itemx .DataObjectId).FirstOrDefault();
if(Itemy!=null)
{
Itemx .ReconTarget = Itemy.AttributeValue;
}
}
Related
I have this relationship between Licitadores and Ofertas
public class Licitador
{
public int Id { get; set; }
public string Nombre { get; set; }
[StringLength(maximumLength: 15)]
public string CodigoSAP { get; set; }
public List<Oferta> Ofertas { get; set; } = new List<Oferta>();
}
public class Oferta
{
[StringLength(maximumLength:6)]
public string Id { get; set; }
[StringLength(maximumLength: 5)]
public string IdPresentada { get; set; }
....
public List<Licitador> Licitadores { get; set; } = new List<Licitador>();
}
And the join table in the context
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LicitacionesEnSolitario>().ToTable("LicitacionesSolitario");
modelBuilder.Entity<Licitador>()
.HasMany(o => o.Ofertas)
.WithMany(of => of.Licitadores)
.UsingEntity<LicitacionesEnSolitario>
(oo => oo.HasOne<Oferta>().WithMany(),
oo => oo.HasOne<Licitador>().WithMany())
.Property(oo => oo.Adjudicado)
.IsRequired();
}
I need this data in my entity/table LicitacionesEnSolitario in addition to PK y FK
public class LicitacionesEnSolitario
{
public int LicitadorId { get; set; }
public string OfertaId { get; set; }
public bool Adjudicado { get; set; }
public string Plazo { get; set; }
public decimal PresupuestoOfertado { get; set; }
public DateTime? FechaAdjudicacion { get; set; }
}
Here I insert the data importing them from another database
public int ImportarLicitacionesEnSolitario()
{
try
{
int registrosAñadidos = 0;
var registrosSAP = _contextSAP.LicitacionesEnSolitario
.FromSqlRaw("sql")
.ToList();
foreach (var registroSAP in registrosSAP)
{
var oferta = _contextBoletus.Ofertas.Find(registroSAP.OfertaId);
var licitador = _contextBoletus.Licitadores.Where(l => l.CodigoSAP == registroSAP.CodigoSAP).FirstOrDefault();
oferta.Licitadores.Add(licitador);
registrosAñadidos +=1;
}
_contextBoletus.SaveChanges();
return registrosAñadidos;
}
catch (Exception ex)
{
throw ex;
}
}
This works fine and insert data in "LicitacionesEnSolitario" but with this fields Adjudicado, Plazo, PresupuestoPfertado y FechaAdjudicacion with nulls.
I don't know how to insert them at the time I insert Licitadores and if I try to update after the Add method using the PKs I just added
foreach (var registroSAP in registrosSAP)
{
var oferta = _contextBoletus.Ofertas.Find(registroSAP.OfertaId);
var licitador = _contextBoletus.Licitadores.Where(l => l.CodigoSAP == registroSAP.CodigoSAP).FirstOrDefault();
oferta.Licitadores.Add(licitador);
var ls = _contextBoletus.Set<LicitacionesEnSolitario>()
.SingleOrDefault(ls => ls.OfertaId == oferta.Id & ls.LicitadorId == licitador.Id);
ls.Adjudicado = registroSAP.Adjudicado;
ls.PresupuestoOfertado = registroSAP.PresupuestoOfertado;
ls.FechaAdjudicacion = registroSAP.FechaAdjudicacion;
registrosAñadidos +=1;
}
_contextBoletus.SaveChanges();
return registrosAñadidos;
I get this error System.NullReferenceException: Object reference not set to an instance of an object.
Any idea, please?
Thanks
This is the best way I found
foreach (var registroSAP in registrosSAP)
{
var oferta = _contextBoletus.Ofertas.Find(registroSAP.OfertaId);
var licitador = _contextBoletus.Licitadores.Where(l => l.CodigoSAP == registroSAP.CodigoSAP).FirstOrDefault();
var ls = _contextBoletus.Set<LicitacionesEnSolitario>().Add(
new LicitacionesEnSolitario
{
LicitadorId = licitador.Id,
OfertaId = oferta.Id,
Adjudicado = registroSAP.Adjudicado,
Plazo = registroSAP.Plazo,
PresupuestoOfertado = registroSAP.PresupuestoOfertado,
FechaAdjudicacion = registroSAP.FechaAdjudicacion
});
registrosAñadidos += 1;
}
Thanks
I have entities like below, which has ICollection relations between them.
How can I take Sum of MakbuzHareketleri entity's IslemTutari field from Police entity?
I think it is necessary to use nested GroupBy, but I couldn't.
public class Police
{
public override string Kod { get; set; }
public EvrakTuru EvrakTuru { get; set; } = EvrakTuru.Police;
public long AcenteId { get; set; }
public string Aciklama { get; set; }
public ICollection<AltPolice> AltPoliceler { get; set; }
}
public class AltPolice
{
public override string Kod { get; set; }
public long PoliceId { get; set; }
public PoliceTuru PoliceTuru { get; set; } = PoliceTuru.Police;
public decimal Prim { get; set; }
public string Aciklama { get; set; }
public Police Police { get; set; }
public virtual ICollection<OdemeBilgileri> OdemeBilgileri { get; set; }
}
public class OdemeBilgileri
{
public long AltPoliceId { get; set; }
public long OdemeTuruId { get; set; }
public BorcTipi BorcTipi { get; set; } = BorcTipi.MusteriBorcu;
public DateTime GirisTarihi { get; set; }
public DateTime Vade { get; set; }
public decimal Tutar { get; set; }
public string Aciklama { get; set; }
public AltPolice AltPolice { get; set; }
public virtual ICollection<MakbuzHareketleri> MakbuzHareketleri { get; set; }
}
public class MakbuzHareketleri
{
public long MakbuzId { get; set; }
public int OdemeBilgileriId { get; set; }
public decimal IslemOncesiTutar { get; set; }
public decimal IslemTutari { get; set; }
public DateTime Vade { get; set; }
public BelgeDurumu BelgeDurumu { get; set; }
public OdemeBilgileri OdemeBilgileri { get; set; }
}
I can do this in Access as follows:
SELECT Police.PoliceNo, AltPolice.PoliceId, Sum(MakbuzHareketleri.IslemTutari) AS ToplaIslemTutari
FROM Police INNER JOIN ((AltPolice INNER JOIN OdemeBilgileri ON AltPolice.Id = OdemeBilgileri.AltPoliceId)
INNER JOIN MakbuzHareketleri ON OdemeBilgileri.Id = MakbuzHareketleri.OdemeBilgileriId) ON Police.Id = AltPolice.PoliceId
WHERE (((OdemeBilgileri.BorcTipi)=1))
GROUP BY Police.PoliceNo, AltPolice.PoliceId, MakbuzHareketleri.BelgeDurumu
HAVING (((MakbuzHareketleri.BelgeDurumu)=2 Or (MakbuzHareketleri.BelgeDurumu)=3));
You should start from the MakbuzHareketleri collection and in order to group by multiple columns you should use an anonymous object and for the having clause you should filter the result selection
var result = context.MakbuzHareketleri.Where(r=> r.OdemeBilgileri.BorcTipi == 1)
.GroupBy(r=> new {r.OdemeBilgileri.AltPolice.PoliceId,r.OdemeBilgileri.AltPolice.Police.PoliceNo,r.BelgeDurumu})
.Select(r=> new {
r.Key.PoliceNo,
r.Key.PoliceId,
ToplaIslemTutari = r.Where(q=> q.BelgeDurumu == 2 || q.BelgeDurumu == 3)
.Select(r=> r.IslemTutari).Sum()
}).ToList();
I list my Police entities in my PoliceBll class like below:
How can I adapt your example here to take Sum of MakbuzHareketleri's IslemTutari field?
public override IEnumerable<BaseEntity> List(Expression<Func<Police, bool>> filter)
{
return BaseList(filter, x => new PoliceL
{
Id = x.Id,
Kod = x.Kod,
EvrakTuru = x.EvrakTuru,
AcenteAdi = x.Acente.Adi,
SigortaTuruAdi = x.SigortaTuru.SigortaTuruAdi,
PoliceNo = x.PoliceNo,
RuhsatSahibiId = x.RuhsatSahibiId,
RuhsatSahibiAdi = x.RuhsatSahibi.CariAdi,
Plaka = x.Plaka,
PolicePrimTutari = x.AltPoliceler.Where(y => y.PoliceId == x.Id && y.PoliceTuru == (x.EvrakTuru == EvrakTuru.Police ? PoliceTuru.Police : PoliceTuru.Tecdit)).Select(y => y.Prim).FirstOrDefault(),
ToplamPrimTutari = x.AltPoliceler.Select(y => y.Prim).DefaultIfEmpty(0).Sum(),
Aciklama = x.Aciklama,
FirmaId = x.AltPoliceler.Where(y => y.PoliceId == x.Id && y.PoliceTuru == PoliceTuru.Police).Select(y => y.FirmaId).FirstOrDefault(),
FirmaAdi = x.AltPoliceler.Where(y => y.PoliceId == x.Id && y.PoliceTuru == PoliceTuru.Police).Select(y => y.Firma.FirmaAdi).FirstOrDefault(),
EklemeTarihi = x.EklemeTarihi,
EkleyenId = x.EkleyenId,
EkleyenAdi = x.Ekleyen.Adi,
DuzenlemeTarihi = x.DuzenlemeTarihi,
DuzenleyenId = x.DuzenleyenId,
DuzenleyenAdi = x.Duzenleyen.Adi,
AltPoliceVar = x.AltPoliceler.Any()
}).OrderBy(x => x.Kod).ToList();
}
It worked for me when I revised the codes like below. So my problem was solved. Thank you for your help.
public override IEnumerable<BaseEntity> List(Expression<Func<Police, bool>> filter)
{
return BaseList(filter, x => new
{
PoliceBilgisi = x,
OdemeBilgileriMusteri = x.AltPoliceler.SelectMany(y => y.OdemeBilgileri.Where(z => z.BorcTipi == BorcTipi.MusteriBorcu)),
}).Select(a => new
{
PoliceBilgi = a.PoliceBilgisi,
MusteridenTahsil = a.OdemeBilgileriMusteri.SelectMany(b => b.MakbuzHareketleri).Where(b =>
b.BelgeDurumu == BelgeDurumu.HesaptaBeklemede ||
b.BelgeDurumu == BelgeDurumu.TahsilKasa ||
b.BelgeDurumu == BelgeDurumu.TahsilBanka ||
b.BelgeDurumu == BelgeDurumu.AvukatYoluylaTahsil ||
b.BelgeDurumu == BelgeDurumu.BMosnTahsil ||
b.BelgeDurumu == BelgeDurumu.KismiTahsilEdildi ||
b.BelgeDurumu == BelgeDurumu.KismiAvukatYoluylaTahsil ||
b.BelgeDurumu == BelgeDurumu.KKPosTahsil)
.Select(b => b.IslemTutari).DefaultIfEmpty(0).Sum(),
})
.Select(x => new PoliceL
{
Id = x.PoliceBilgi.Id,
Kod = x.PoliceBilgi.Kod,
EvrakTuru = x.PoliceBilgi.EvrakTuru,
AcenteAdi = x.PoliceBilgi.Acente.Adi,
SigortaTuruAdi = x.PoliceBilgi.SigortaTuru.SigortaTuruAdi,
PoliceNo = x.PoliceBilgi.PoliceNo,
RuhsatSahibiId = x.PoliceBilgi.RuhsatSahibiId,
RuhsatSahibiAdi = x.PoliceBilgi.RuhsatSahibi.CariAdi,
Plaka = x.PoliceBilgi.Plaka,
PolicePrimTutari = x.PoliceBilgi.AltPoliceler.Where(y => y.PoliceId == x.PoliceBilgi.Id && y.PoliceTuru == (x.PoliceBilgi.EvrakTuru == EvrakTuru.Police ? PoliceTuru.Police : PoliceTuru.Tecdit)).Select(y => y.Prim).FirstOrDefault(),
ToplamPrimTutari = x.PoliceBilgi.AltPoliceler.Select(y => y.Prim).DefaultIfEmpty(0).Sum(),
Aciklama = x.PoliceBilgi.Aciklama,
FirmaId = x.PoliceBilgi.AltPoliceler.Where(y => y.PoliceId == x.PoliceBilgi.Id && y.PoliceTuru == PoliceTuru.Police).Select(y => y.FirmaId).FirstOrDefault(),
FirmaAdi = x.PoliceBilgi.AltPoliceler.Where(y => y.PoliceId == x.PoliceBilgi.Id && y.PoliceTuru == PoliceTuru.Police).Select(y => y.Firma.FirmaAdi).FirstOrDefault(),
EklemeTarihi = x.PoliceBilgi.EklemeTarihi,
EkleyenId = x.PoliceBilgi.EkleyenId,
EkleyenAdi = x.PoliceBilgi.Ekleyen.Adi,
DuzenlemeTarihi = x.PoliceBilgi.DuzenlemeTarihi,
DuzenleyenId = x.PoliceBilgi.DuzenleyenId,
DuzenleyenAdi = x.PoliceBilgi.Duzenleyen.Adi,
AltPoliceVar = x.PoliceBilgi.AltPoliceler.Any(),
MusteridenTahsil = x.MusteridenTahsil,
}).OrderBy(x => x.Kod).ToList();
}
I have current setup, with a Select indexer-projection (entity, index) (see SubRubrics). If i leave the indexer out, the problem is solved... However if I leave out the SubRubricItems then I can use the indexer. Is it only on the last select projection I can use it, or..?
Below linq projection, error message and more info.
await _db
.Exams
.AsNoTracking()
.Include(exam => exam.Stations)
.ThenInclude(station => station.Rubrics)
.ThenInclude(rubric => rubric.SubRubrics)
.ThenInclude(subRubric => subRubric.Items)
.Select(exam => new Result.ExamViewModel
{
Id = exam.Id,
Name = exam.Name,
Stations = exam.Stations.Select(station => new Result.StationViewModel
{
Id = station.Id,
Description = station.Description,
Rubrics = station.Rubrics.Select(rubric => new Result.RubricViewModel
{
Id = rubric.Id,
Name = rubric.Name,
Info = rubric.Info,
SubRubrics = rubric.SubRubrics.Select((subRubric, index) => new Result.SubRubricViewModel
{
Id = subRubric.Id,
Order = index,
Name = subRubric.Name,
Info = subRubric.Info,
Type = subRubric.Type.ToString(),
Items = subRubric.Items.Select(item => new Result.SubRubricItemViewModel
{
Id = item.Id,
Name = item.Name
})
})
})
})
})
.ToListAsync()
This provides this error which I don't understand :/
InvalidOperationException: Processing of the LINQ expression '(MaterializeCollectionNavigation(
navigation: Navigation: Rubric.SubRubrics,
subquery: (NavigationExpansionExpression
Source: DbSet<SubRubric>
.Where(s0 => !(s0.IsDeleted))
.Where(s0 => EF.Property<Nullable<long>>(r, "Id") != null && EF.Property<Nullable<long>>(r, "Id") == EF.Property<Nullable<long>>(s0, "RubricId"))
PendingSelector: s0 => (NavigationTreeExpression
Value: (EntityReference: SubRubric | IncludePaths: Items)
Expression: s0)
)
.Where(i => EF.Property<Nullable<long>>((NavigationTreeExpression
Value: (EntityReference: Rubric | IncludePaths: Version SubRubrics->...)
Expression: r), "Id") != null && EF.Property<Nullable<long>>((NavigationTreeExpression
Value: (EntityReference: Rubric | IncludePaths: Version SubRubrics->...)
Expression: r), "Id") == EF.Property<Nullable<long>>(i, "RubricId")))
.AsQueryable()
.Select((subRubric, index) => new SubRubricViewModel{
Id = subRubric.Id,
Order = index,
Name = subRubric.Name,
Info = subRubric.Info,
Type = subRubric.Type.ToString(),
Items = subRubric.Items
.AsQueryable()
.Select(item => new SubRubricItemViewModel{
Id = item.Id,
Name = item.Name
}
)
}
)' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.
This used to work, until I added the extra SubRubricItems select for the Items model, aka
Items = subRubric.Items.Select(item => new Result.SubRubricItemViewModel
{
Id = item.Id,
Name = item.Name
})
For reference sake, this is the viewmodel that's being projected into:
public sealed class Result
{
public IEnumerable<ExamViewModel> Exams { get; set; }
public sealed class ExamViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public IEnumerable<StationViewModel> Stations { get; set; }
}
public sealed class StationViewModel
{
public long Id { get; set; }
public string Description { get; set; }
public IEnumerable<RubricViewModel> Rubrics { get; set; }
}
public sealed class RubricViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public string Info { get; set; }
public IEnumerable<SubRubricViewModel> SubRubrics { get; set; }
}
public sealed class SubRubricViewModel
{
public long Id { get; set; }
public int Order { get; set; }
public string Name { get; set; }
public string Info { get; set; }
public string Type { get; set; }
public IEnumerable<SubRubricItemViewModel> Items { get; set; }
}
public sealed class SubRubricItemViewModel
{
public long Id { get; set; }
public int Order { get; set; }
public string Name { get; set; }
public string Info { get; set; }
public string Type { get; set; }
}
}
That can't be translated to SQL. So either run the SQL query before the .Select(),
.ThenInclude(subRubric => subRubric.Items)
.AsEnumerable()
.Select(exam => new Result.ExamViewModel
or remove the Includes (they don't do anything when you have a custom projection, and thereby change the query)
SubRubrics = rubric.SubRubrics.Select((subRubric) => new Result.SubRubricViewModel
{
Id = subRubric.Id,
Order = 0, . . .
and fill in the Order property on the view models afterwards.
I'm using the solution provided by this link: AutoMapper don't work with entity EF Core
My problem is when using $top, #odata.count always return the number informed in $top but should return the number of total record.
I know that ODataQueryOptions has a property “Count”, but I don't know if it's possible to use to solve the problem
I'm using the below the code provided by Дмитрий Краснов in his question including the solution by Ivan Stoev:
There is entities:
public class LessonCatalog {
public string Name { get; set; }
public int? ImageId { get; set; }
public virtual Image Image { get; set; }
public virtual ICollection<Lesson> Lessons { get; set; }
}
public class Lesson {
public string Name { get; set; }
public string Description { get; set; }
public int? ImageId { get; set; }
public virtual Image Image { get; set; }
public int LessonCatalogId { get; set; }
public virtual LessonCatalog LessonCatalog { get; set; }
}
Views:
public class LessonView {
public string Name { get; set; }
public string Description { get; set; }
public int? ImageId { get; set; }
public ImageView Image { get; set; }
public int LessonCatalogId { get; set; }
public LessonCatalogView LessonCatalog { get; set; }
}
public class LessonCatalogView {
public string Name { get; set; }
public int? ImageId { get; set; }
public ImageView Image { get; set; }
public IEnumerable<LessonView> Lessons { get; set; }
}
My maps:
CreateMap<LessonCatalog, LessonCatalogView>()
.ForMember(dest => dest.Image, map => map.ExplicitExpansion())
.ForMember(dest => dest.Lessons, map => map.ExplicitExpansion());
CreateMap<Lesson, LessonView>()
.ForMember(dest => dest.LessonCatalog, map => map.ExplicitExpansion());
In my repository:
protected readonly DbContext _context;
protected readonly DbSet<TEntity> _entities;
public Repository(DbContext context) {
_context = context;
_entities = context.Set<TEntity>();
}
public IEnumerable<TView> GetOData<TView>(ODataQueryOptions<TView> query,
Expression<Func<TEntity, bool>> predicate = null) {
IQueryable<TEntity> repQuery = _entities.AsQueryable();
IQueryable res;
if (predicate != null) repQuery = _entities.Where(predicate);
if (query != null) {
string[] expandProperties = GetExpands(query);
//!!!
res = repQuery.ProjectTo<TView>(Mapper.Configuration, null, expandProperties);
//!!!
var settings = new ODataQuerySettings();
var ofilter = query.Filter;
var orderBy = query.OrderBy;
var skip = query.Skip;
var top = query.Top;
if (ofilter != null) res = ofilter.ApplyTo(res, settings);
if (orderBy != null) res = orderBy.ApplyTo(res, settings);
if (skip != null) res = skip.ApplyTo(res, settings);
if (top != null) res = top.ApplyTo(res, settings);
} else {
res = repQuery.ProjectTo<TView>(Mapper.Configuration);
}
return (res as IQueryable<TView>).AsEnumerable();
}
If my query result has 1007 records, and I use
…$count=true&$top=5
the result for count should be
"#odata.count": 1007
But instead the result is always
"#odata.count": 5
Using SQL Server Profile I can see that the Select for count is including the “top”. So, how to avoid this to happen?
I received a help from the Github Guy (thanks to #Gennady Pundikov) and could now answer this question.
I changed the GetOData Method to get the Count before apply others settings:
public IEnumerable<TView> GetOData<TView>(ODataQueryOptions<TView> query,
Expression<Func<TEntity, bool>> predicate = null) {
IQueryable<TEntity> repQuery = _entities.AsQueryable();
IQueryable res;
if (predicate != null) repQuery = _entities.Where(predicate);
if (query != null) {
string[] expandProperties = GetExpands(query);
//!!!
res = repQuery.ProjectTo<TView>(Mapper.Configuration, null, expandProperties);
//!!!
var settings = new ODataQuerySettings();
var ofilter = query.Filter;
var orderBy = query.OrderBy;
var skip = query.Skip;
var top = query.Top;
if (ofilter != null) res = ofilter.ApplyTo(res, settings);
if (query.Count?.Value == true)
{
// We should calculate TotalCount only with filter
// http://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part2-url-conventions.html#_Toc371341773
// 4.8 Addressing the Count of a Collection
// "The returned count MUST NOT be affected by $top, $skip, $orderby, or $expand.
query.Request.ODataFeature().TotalCount = ((IQueryable<TView>)res).LongCount();
}
if (top != null) res = top.ApplyTo(res, settings);
if (orderBy != null) res = orderBy.ApplyTo(res, settings);
if (skip != null) res = skip.ApplyTo(res, settings);
} else {
res = repQuery.ProjectTo<TView>(Mapper.Configuration);
}
return (res as IQueryable<TView>).AsEnumerable();
}
Here is what I have:
public class StudentHealthInfoType
{
public int StudentHealthInfoId { get; set; }
public bool? HasAllergies { get; set; }
public List<HealthInfoMedicationType> HealthInfoMedicationType { get; set;}
}
public class HealthInfoMedicationType
{
public int HealthInfoMedicationId { get; set; }
public string MedicationName { get; set; }
}
var result = (from u in context.StudentHealthInfos
from m in context.HealthInfoMedications
where u.RegistrationId == registrationId
&& u.StudentHealthInfoId == m.StudentHealthInfoId
select new StudentHealthInfoType
{ StudentHealthInfoId = u.StudentHealthInfoId,
HasAllergies = u.HasAllergies, HealthInfoMedicationType = new HealthInfoMedicationType
{ HealthInfoMedicationId = m.HealthInfoMedicationId,
MedicationName = m.MedicationName
}
}).FirstOrDefault();
I get this error which is show at HealthInfoMedicationType = new HealthInfoMedicationType
Cannot implicitly convert type
'Dis.QueryManager.HealthFormTypes.HealthInfoMedicationType' to
'System.Collections.Generic.List'
HealthInfoMedicationType needs to be a collection of items returned for one StudentHealthInfoType record. How do I need to setup my objects and then cast them so this query works?
Please try this if you want to query for a particular registration id and list of HealthInfoMedications you can do like this .
var result = context.StudentHealthInfos
.Include(x=>x.HealthInfoMedicationType).FirstOrDefault(f => f.RegistrationId == 1);
// Result will be StudentHealthInfoType with list of HealthInfoMedicationType