Linq group by in sum column from with where clause - entity-framework

public class PowerPlantsBudgetUsage
{
public int PowerPlantID { get; set; }
public int TotalWork { get; set; }
public int ElectricalWorkNo { get; set; }
public int MechanicalWorkNo { get; set; }
public int CivilWorkNo { get; set; }
public int AdminWorkNo { get; set; }
public int VehicleWorkNo { get; set; }
[DisplayFormat(DataFormatString = "{0:N}")]
public decimal ElectricalBudgetOnly { get; set; }
public decimal Total { get; set; }
public string PowerPlantName { get; set; }
}
public IActionResult Total()
{
var query = _context.REHPData.Include(r => r.PowerPlants).Include(r => r.WorkCategories).GroupBy(r => r.PowerPlantID).Select(s => new PowerPlantsBudgetUsage
{
PowerPlantID = s.Key,
PowerPlantName = s.Select(p => p.PowerPlants.PowerPlantName).First(),
TotalWork = s.Count(),
ElectricalWorkNo = s.Count(x => x.WorkCategoriesID == 1),
MechanicalWorkNo = s.Count(x => x.WorkCategoriesID == 2),
CivilWorkNo = s.Count(x => x.WorkCategoriesID == 3),
AdminWorkNo = s.Count(x => x.WorkCategoriesID == 4),
VehicleWorkNo = s.Count(x => x.WorkCategoriesID == 6),
Total = s.Sum(x => x.ApprovedAmount),
ElectricalBudgetOnly = s.Sum(x => x.ApprovedAmount).Where(x=>x.WorkCategoriesID==1) /*this column result is s.Sum(x => x.ApprovedAmount).Where(WorkCategoriesID == 1) */
}).ToList();
return View(query);
}
my problems is ElectricalBudgetOnly is sum from ApprovedAmount where CategoriesID == 1
powrplantname is test test test test test so on...

Your mistake is that you have it swapped.
//...
ElectricalBudgetOnly = s.Where(x => x.WorkCategoriesID == 1).Sum(x => x.ApprovedAmount)
Apply the where first and then sum the result of the where

Related

How to insert payload data in many-to-many relationships with EF Core 5

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

How can I take Sum of 3 levels down entity field, which has ICollection relation between them

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();
}

How to get all columns' max, min, mean values

I am trying to get max, min and mean of the values with using
context.SystemUser
.Include(x => x.Stores)
.ThenInclude(a => a.StoreStockDetail)
.Where(b => b.UserName == userName)
.Select(c => new
{
/*max, min, mean values of columns of StoreStockDetail*/
});
public class SystemUser
{
public int Id { get; set; }
public virtual List<Store> Stores { get; set; }
public SystemUser()
{
this.Stores = new List<Store>();
}
}
public class Store
{
public int Id { get; set; }
public virtual StoreStockDetail StoreStockDetail { get; set; }
}
public class StoreStockDetail
{
public int Id { get; set; }
public int BackStore { get; set; }
public int FrontStore { get; set; }
public int ShoppingWindow { get; set; }}
public int StoreId { get; set; }
public virtual Store Store { get; set; }
}
I need to have max, min and mean report of the columns BackStore, FrontStore and ShoppingWindow columns.
Thank you
Instead of using a sequence of LINQ expressions, you could flatten the list of Stores in the SystemUser first and then use the result to find max, min and average. Try this:
var stores = context.SystemUser
.Include(x => x.Stores)
.ThenInclude(a => a.StoreStockDetail)
.Where(b => b.UserName == userName).SelectMany(user => user.Stores);
var report = new
{
FrontStoreMin = stores.Min(store => store.StoreStockDetail.FrontStore),
FrontStoreMax = stores.Max(store => store.StoreStockDetail.FrontStore),
FrontStoreMean = stores.Average(store => store.StoreStockDetail.FrontStore),
// do the same for BackStore and ShoppingWindow
};

Entity Framework 6 several one-to-mmay

Onother problem with Entity Framework 6. I don't know why, but I have some trouble to get back my object frome the database when I queue 2 one-to-many relationships.
My plain objects
public class Plan
{
public int id { get; set; }
public int largeur { get; set; }
public int longueur { get; set; }
public string nom { get; set; }
public virtual List<Etage> listEtages { get; set; }
public Plan() { }
}
public class Etage
{
public int id { get; set; }
public virtual List<PositionModule> listPositionModule { get; set; }
public virtual Plan plan { get; set; }
public Etage() { }
}
public class PositionModule
{
public int id { get; set; }
public int x1 { get; set; }
public int x2 { get; set; }
public int y1 { get; set; }
public int y2 { get; set; }
public string lineId { get; set; }
public virtual Module module { get; set; }
public virtual Etage etage { get; set; }
public PositionModule() { }
}
public class Module
{
public int id { get; set; }
public string libe { get; set; }
public string coupePrincipe { get; set; }
public virtual TModule typeModule { get; set; }
public decimal prix { get; set; }
public Module()
{
}
}
Ef6 fluent mapping
public class PlanConfiguration : EntityTypeConfiguration<Plan>
{
public PlanConfiguration()
{
ToTable("Plan");
HasKey<int>(a => a.id);
Property<int>(a => a.largeur).IsRequired();
Property<int>(a => a.longueur).IsRequired();
Property(a => a.nom).HasColumnType("varchar").HasMaxLength(50);
}
}
public class EtageConfiguration : EntityTypeConfiguration<Etage>
{
public EtageConfiguration()
{
ToTable("Etage");
HasKey<int>(a => a.id);
HasRequired<Plan>(x => x.plan).WithMany(x => x.listEtages);
}
}
public class PositionModuleConfiguration : EntityTypeConfiguration<PositionModule>
{
public PositionModuleConfiguration()
{
ToTable("PositionModule");
HasKey<int>(a => a.id);
HasRequired<Module>(a => a.module);
HasRequired<Etage>(x => x.etage).WithMany(x => x.listPositionModule);
Property<int>(x => x.x1);
Property<int>(x => x.x2);
Property<int>(x => x.y1);
Property<int>(x => x.y2);
Property(a => a.lineId).HasColumnType("varchar").HasMaxLength(30);
}
}
public class ModuleConfiguration : EntityTypeConfiguration<Module>
{
public ModuleConfiguration()
{
ToTable("Module");
HasKey<int>(a => a.id);
HasOptional<TModule>(a => a.typeModule);
Property(a => a.libe).HasColumnType("varchar").HasMaxLength(150);
Property(a => a.coupePrincipe).HasColumnType("varchar");
}
}
At the moment I'm able to store a Plan which has a list of Etage with many PositionModule.
But when I want to get back my all plan with a get by id, the listEtages is empty.
By checking on the database, all foreign keys are good and I use the one-to-many with two other (simplier) objects and it works fine...
It's my first project with EF6 so if you have any tips to share, it will be a pleasure.
Thanks
Update
My DTOs
public class PlanDTO
{
public int id { get; set; }
public int largeur { get; set; }
public int longueur { get; set; }
public string nom { get; set; }
public List<EtageDTO> lesEtages { get; set; }
public PlanDTO()
{
lesEtages = new List<EtageDTO>();
}
}
public class EtageDTO
{
public int id { get; set; }
public List<PositionModuleDTO> lesModules { get; set; }
public PlanDTO plan { get; set; }
public EtageDTO()
{
lesModules = new List<PositionModuleDTO>();
plan = new PlanDTO();
}
}
public class PositionModuleDTO
{
public int id { get; set; }
public int x1 { get; set; }
public int x2 { get; set; }
public int y1 { get; set; }
public int y2 { get; set; }
public string lineId { get; set; }
public ModuleDTO module { get; set; }
public EtageDTO etage { get; set; }
public PositionModuleDTO()
{
module = new ModuleDTO();
}
}
public class ModuleDTO
{
public string libe { get; set; }
public int id { get; set; }
public string coupePrincipe { get; set; }
public TModule typeModule { get; set; }
}
How I mapp my DTOs and Plain objects (with automapper)
--- ViewModelToDomain ---
CreateMap<PlanDTO, Plan>()
.ForMember(g => g.id, map => map.MapFrom(vm => vm.id))
.ForMember(g => g.largeur, map => map.MapFrom(vm => vm.largeur))
.ForMember(g => g.longueur, map => map.MapFrom(vm => vm.longueur))
.ForMember(g => g.nom, map => map.MapFrom(vm => vm.nom))
.ForMember(g => g.listEtages, map => map.MapFrom(vm => vm.lesEtages));
CreateMap<EtageDTO, Etage>()
.ForMember(g => g.id, map => map.MapFrom(vm => vm.id))
.ForMember(g => g.listPositionModule, map => map.MapFrom(vm => vm.lesModules))
.ForMember(g => g.plan, map => map.MapFrom(vm => vm.plan));
CreateMap<PositionModuleDTO, PositionModule>()
.ForMember(g => g.id, map => map.MapFrom(vm => vm.id))
.ForMember(g => g.x1, map => map.MapFrom(vm => vm.x1))
.ForMember(g => g.x2, map => map.MapFrom(vm => vm.x2))
.ForMember(g => g.y1, map => map.MapFrom(vm => vm.y1))
.ForMember(g => g.y2, map => map.MapFrom(vm => vm.y2))
.ForMember(g => g.module, map => map.MapFrom(vm => vm.module))
.ForMember(g => g.etage, map => map.MapFrom(vm => vm.etage));
CreateMap<ModuleDTO, Module>()
.ForMember(g => g.id, map => map.MapFrom(vm => vm.id))
.ForMember(g => g.libe, map => map.MapFrom(vm => vm.libe))
.ForMember(g => g.typeModule, map => map.MapFrom(vm => vm.typeModule))
.ForMember(g => g.coupePrincipe, map => map.MapFrom(vm => vm.coupePrincipe));
--- DomainToViewModel ---
CreateMap<Plan, PlanDTO>();
CreateMap<Etage, EtageDTO>();
CreateMap<PositionModule, PositionModuleDTO>();
CreateMap<Module, ModuleDTO>();
The controller where I create and try to get back my plan
[HttpPost]
public ActionResult SavePlan(PlanDTO plan)
{
if (plan != null)
{
Plan planP = new Plan();
plan.nom = "test";
planP=Mapper.Map<PlanDTO, Plan>(plan);
try
{
_planService.Create(planP);//The plan is create
/*
refers to
public virtual void Insert(T entity)
{
dbSet.Add(entity);
}
*/
_planService.Save();
}
catch(Exception e)
{
throw (e);
}
return Json("Success");
}
else
{
return Json("An Error Has occoured");
}
}
[HttpPost]
public JsonResult GetPlan(int id)
{
try
{
List<ModuleDTO> lesModules = Mapper.Map<List<Module>, List<ModuleDTO>>(_moduleService.DonneTous().ToList());
PlanDTO plan = Mapper.Map<Plan, PlanDTO>(_planService.Get(id));//I have id, largeur, longueure and nom but listEtages is empty (all data are in database)
/*
refers to
public virtual T GetById(int id)
{
return dbSet.Find(id);
}
*/
return Json(plan);
}
catch(Exception e)
{
return Json("An Error Has occoured");
}
}

Update list object based on other LINQ / LAMBDA

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;
}
}