I am still an ASP.NET amateur and I've been working on an application that needs to calculate the hours an employee has worked if no special events have come up e.g the employee has been sick, I have 2 tables in my database, 1 with the employees. and a second table which holds the events. the events table is filled through a calendar and holds info like dates and who made the event.
My situation:
When the user clicks on an employee's detail page. I want the corresponding record of the employee, and the events he made. So I am assuming that I am looking for a join with linq.
An employee can make more than 1 event, let's say an employee needs to work overtime 3 days this month. then on the detail page, it should select the employee from the employee table and the 3 events from the events table.
Update
Thanks to Vladimir's help, a whole lot of errors are gone and the query works. Though it does not completely work as expected yet. it currently returns 1 employee and 1 event. While the employee that I am testing with, should have 4 events returned.
This is my Context
namespace hrmTool.Models
{
public class MedewerkerMeldingContext : DbContext
{
public MedewerkerMeldingContext() : base("name=temphrmEntities") { }
public DbSet<medewerker> medewerker { get; set; }
public DbSet<medewerker_melding> medewerker_melding { get; set; }
}
}
My current viewModel
namespace hrmTool.Models
{
public class MedewerkerMeldingViewModel
{
//Medewerker tabel
public int ID { get; set; }
public string roepnaam { get; set; }
public string voorvoegsel { get; set; }
public string achternaam { get; set; }
public string tussenvoegsel { get; set; }
public string meisjesnaam { get; set; }
public Nullable<System.DateTime> datum_in_dienst { get; set; }
public Nullable<System.DateTime> datum_uit_dienst { get; set; }
public int aantal_km_woon_werk { get; set; }
public bool maandag { get; set; }
public Nullable<System.TimeSpan> ma_van { get; set; }
public Nullable<System.TimeSpan> ma_tot { get; set; }
public bool dinsdag { get; set; }
public Nullable<System.TimeSpan> di_van { get; set; }
public Nullable<System.TimeSpan> di_tot { get; set; }
public bool woensdag { get; set; }
public Nullable<System.TimeSpan> wo_van { get; set; }
public Nullable<System.TimeSpan> wo_tot { get; set; }
public bool donderdag { get; set; }
public Nullable<System.TimeSpan> do_van { get; set; }
public Nullable<System.TimeSpan> do_tot { get; set; }
public bool vrijdag { get; set; }
public Nullable<System.TimeSpan> vr_van { get; set; }
public Nullable<System.TimeSpan> vr_tot { get; set; }
public bool zaterdag { get; set; }
public Nullable<System.TimeSpan> za_van { get; set; }
public Nullable<System.TimeSpan> za_tot { get; set; }
public bool zondag { get; set; }
public Nullable<System.TimeSpan> zo_van { get; set; }
public Nullable<System.TimeSpan> zo_tot { get; set; }
//Medewerker_Melding combi tabel
public int medewerkerID { get; set; }
public int meldingID { get; set; }
public System.DateTime datum_van { get; set; }
public Nullable<System.DateTime> datum_tot { get; set; }
public int MM_ID { get; set; }
public virtual ICollection<medewerker_melding> medewerker_melding { get; set; }
public virtual medewerker medewerker { get; set; }
}
}
My current query
using (var context = new MedewerkerMeldingContext())
{
var medewerkers = context.medewerker;
var medewerker_meldings = context.medewerker_melding;
var testQuery = from m in medewerkers
join mm in medewerker_meldings on m.ID equals mm.medewerkerID
where m.ID == id
select new MedewerkerMeldingViewModel
{
ID = m.ID,
roepnaam = m.roepnaam,
voorvoegsel = m.voorvoegsel,
achternaam = m.achternaam,
tussenvoegsel = m.tussenvoegsel,
meisjesnaam = m.meisjesnaam,
datum_in_dienst = m.datum_in_dienst,
datum_uit_dienst = m.datum_uit_dienst,
aantal_km_woon_werk = m.aantal_km_woon_werk,
maandag = m.maandag,
ma_van = m.ma_van,
ma_tot = m.ma_tot,
dinsdag = m.dinsdag,
di_van = m.di_van,
di_tot = m.di_tot,
woensdag = m.woensdag,
wo_van = m.wo_van,
wo_tot = m.wo_tot,
donderdag = m.donderdag,
do_van = m.do_van,
do_tot = m.do_tot,
vrijdag = m.vrijdag,
vr_van = m.vr_van,
vr_tot = m.vr_tot,
zaterdag = m.zaterdag,
za_van = m.za_van,
za_tot = m.za_tot,
zondag = m.zondag,
zo_van = m.zo_van,
zo_tot = m.zo_tot,
medewerkerID = mm.medewerkerID,
meldingID = mm.meldingID,
datum_van = mm.datum_van,
datum_tot = mm.datum_tot,
MM_ID = mm.ID
};
var getQueryResult = testQuery.FirstOrDefault();
Debug.WriteLine("Debug testQuery" + testQuery);
Debug.WriteLine("Debug getQueryResult: "+ getQueryResult);
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (testQuery == null)
{
return HttpNotFound();
}
return View(getQueryResult);
}
Returns: 1 instance of employee and only 1 event
Expected return: 1 instance of employee, 4 events
In your context DbContext is missing - so Linq to Entity can not find corresponding implementation of the query. And also DbContext operates with the
DbSets - so try:
public class MedewerkerMeldingContext : DbContext
{
public MedewerkerMeldingContext () : base(ConnectionStringKey)
{
};
public DbSet<medewerker> medewerker { get; set; }
public DbSet<medewerker_melding> medewerker_melding { get; set; }
}
then
using (var context = new MedewerkerMeldingContext())
{
var medewerkers = context.medewerker;
var medewerker_meldings = context.medewerker_melding;
var testQuery = from m in medewerkers
join mm in medewerker_meldings on m.ID equals mm.medewerkerID
where m.ID == id
select new MedewerkerMeldingViewModel
{
ID = m.ID,
roepnaam = m.roepnaam,
voorvoegsel = m.voorvoegsel,
achternaam = m.achternaam,
tussenvoegsel = m.tussenvoegsel,
meisjesnaam = m.meisjesnaam,
datum_in_dienst = m.datum_in_dienst,
datum_uit_dienst = m.datum_uit_dienst,
aantal_km_woon_werk = m.aantal_km_woon_werk,
maandag = m.maandag,
ma_van = m.ma_van,
ma_tot = m.ma_tot,
dinsdag = m.dinsdag,
di_van = m.di_van,
di_tot = m.di_tot,
woensdag = m.woensdag,
wo_van = m.wo_van,
wo_tot = m.wo_tot,
donderdag = m.donderdag,
do_van = m.do_van,
do_tot = m.do_tot,
vrijdag = m.vrijdag,
vr_van = m.vr_van,
vr_tot = m.vr_tot,
zaterdag = m.zaterdag,
za_van = m.za_van,
za_tot = m.za_tot,
zondag = m.zondag,
zo_van = m.zo_van,
zo_tot = m.zo_tot,
medewerkerID = mm.medewerkerID,
meldingID = mm.meldingID,
datum_van = mm.datum_van,
datum_tot = mm.datum_tot,
MM_ID = mm.ID
};
Debug.WriteLine("Debug testQuery" + testQuery);
var getQueryResult = testQuery.ToList();
Debug.WriteLine("Debug getQueryResult: " + getQueryResult);
var resultDictionary = getQueryResult.GroupBy(x => x.ID).ToDictionary(y => y.Key, z => z.ToList());
Debug.WriteLine("resultDictionary: " + resultDictionary);
var firstItem = resultDictionary.Values.First();
Debug.WriteLine("FirstItem: " + firstItem);
var Entity = new newEntity
{
//ID = firstItem.ID,
ID = firstItem.Select(x => x.ID).First(),
roepnaam = firstItem.Select(x => x.roepnaam).First(),
voorvoegsel = firstItem.Select(x => x.voorvoegsel).First(),
achternaam = firstItem.Select(x => x.achternaam).First(),
tussenvoegsel = firstItem.Select(x => x.tussenvoegsel).First(),
meisjesnaam = firstItem.Select(x => x.meisjesnaam).First(),
datum_in_dienst = firstItem.Select(x => x.datum_in_dienst).First(),
datum_uit_dienst = firstItem.Select(x => x.datum_uit_dienst).First(),
aantal_km_woon_werk = firstItem.Select(x => x.aantal_km_woon_werk).First(),
maandag = firstItem.Select(x => x.maandag).First(),
ma_van = firstItem.Select(x => x.ma_van).First(),
ma_tot = firstItem.Select(x => x.ma_tot).First(),
dinsdag = firstItem.Select(x => x.dinsdag).First(),
di_van = firstItem.Select(x => x.di_van).First(),
di_tot = firstItem.Select(x => x.di_tot).First(),
woensdag = firstItem.Select(x => x.woensdag).First(),
wo_van = firstItem.Select(x => x.wo_van).First(),
wo_tot = firstItem.Select(x => x.wo_tot).First(),
donderdag = firstItem.Select(x => x.donderdag).First(),
do_van = firstItem.Select(x => x.do_van).First(),
do_tot = firstItem.Select(x => x.do_tot).First(),
vrijdag = firstItem.Select(x => x.vrijdag).First(),
vr_van = firstItem.Select(x => x.vr_van).First(),
vr_tot = firstItem.Select(x => x.vr_tot).First(),
zaterdag = firstItem.Select(x => x.zaterdag).First(),
za_van = firstItem.Select(x => x.za_van).First(),
za_tot = firstItem.Select(x => x.za_tot).First(),
zondag = firstItem.Select(x => x.zondag).First(),
zo_van = firstItem.Select(x => x.zo_van).First(),
zo_tot = firstItem.Select(x => x.zo_tot).First()
};
Debug.WriteLine("Entity: " + Entity);
var plainValues = resultDictionary.Values.SelectMany(x => x).ToList();
var resultSchedule = plainValues.Select(x => new medewerker_melding
{
medewerkerID = x.medewerkerID,
meldingID = x.meldingID,
datum_van = x.datum_van,
datum_tot = x.datum_tot,
ID = x.MM_ID
}).ToList();
Entity.medewerker_melding = resultSchedule;
}
You need to check whether MedewerkerMeldingContext dbC = new MedewerkerMeldingContext(); is implementing IEnumerable<T> else, you will not be able to preform the desired action on the table.
This kind of error (Could not find an implementation of the query
pattern) usually occurs when:
You are missing LINQ namespace usage (using System.Linq)
Typeyou are querying does not implement IEnumerable<T>
What i'd recommend, first check the namespace.
Second check for the IEnumerable<T> implementation.
Your query is good enough, you take the context and perform the linq, no issue here. It is 90% that you forgot the namespace since context is already implementing the IEnumerable<T> interface.
Related
Given the following code example, how do I:
Get the commented out lines in the unfiltered list to work (without changing the definition of Result)?
Get the commented out lines in the filtered list to work (without changing the definition of Result)? From my maths it should give 32 records. Hopefully my output intent is clear enough for others to understand
Any questions feel free to ask
Regards
Kyle
//Populate data
var alphas = new List<Alpha>();
for (int a = 1; a <= 10; a++)
{
var alpha = new Alpha() { Id = a, Name = "A" + a };
for (int b = 1; b <= 10; b++)
{
var beta = new Beta() { Id = b, Name = "B" + b };
for (int c = 1; c <= 10; c++)
{
var charlie = new Charlie() { Id = c, Name = "C" + c };
for (int d = 1; d <= 10; d++)
{
var delta = new Delta() { Id = d, Name = "D" + d };
charlie.Deltas.Add(delta);
}
beta.Charlies.Add(charlie);
}
alpha.Betas.Add(beta);
}
alphas.Add(alpha);
}
//Get results into required format without filtering
var unfilteredResults = alphas.Select(a => new Result
{
AId = a.Id,
AName = a.Name,
//BId = a.Betas.Select(b => b.Id),
//BName = a.Betas.Select(b => b.Name),
//CId = a.Betas.Select(b => b.Charlies.Select(c => c.Id)),
//CName = a.Betas.Select(b => b.Charlies.Select(c => c.Name)),
//DId = a.Betas.Select(b => b.Charlies.Select(c => c.Deltas.Select(d => d.Id))),
//DName = a.Betas.Select(b => b.Charlies.Select(c => c.Deltas.Select(d => d.Name)))
});
var whiteListAIds = new List<int>() { 1, 2 };
var whiteListBIds = new List<int>() { 3, 4 };
var whiteListCIds = new List<int>() { 5, 6 };
var whiteListDIds = new List<int>() { 7, 8 };
//Get results into required format with filtering
var filteredResults = alphas.Where(a => whiteListAIds.Contains(a.Id)).Select(a => new Result
{
AId = a.Id,
AName = a.Name,
//BId = a.Betas.Where(b => whiteListBIds.Contains(b.Id)).Select(b => b.Id),
//BName = a.Betas.Where(b => whiteListBIds.Contains(b.Id)).Select(b => b.Name),
//CId = a.Betas.Where(b => whiteListBIds.Contains(b.Id)).Select(b => b.Charlies.Where(c => whiteListCIds.Contains(c.Id)).Select(c => c.Id)),
//CName = a.Betas.Where(b => whiteListBIds.Contains(b.Id)).Select(b => b.Charlies.Where(c => whiteListCIds.Contains(c.Id)).Select(c => c.Name)),
//DId = a.Betas.Where(b => whiteListBIds.Contains(b.Id)).Select(b => b.Charlies.Where(c => whiteListCIds.Contains(c.Id)).Select(c => c.Deltas.Where(d => whiteListDIds.Contains(d.Id)).Select(d => d.Id))),
//DName = a.Betas.Where(b => whiteListBIds.Contains(b.Id)).Select(b => b.Charlies.Where(c => whiteListCIds.Contains(c.Id)).Select(c => c.Deltas.Where(d => whiteListDIds.Contains(d.Id)).Select(d => d.Name)))
});
class Alpha
{
public int Id { get; set; }
public string Name { get; set; }
public List<Beta> Betas { get; set; } = new List<Beta>();
}
class Beta
{
public int Id { get; set; }
public string Name { get; set; }
public List<Charlie> Charlies { get; set; } = new List<Charlie>();
}
class Charlie
{
public int Id { get; set; }
public string Name { get; set; }
public List<Delta> Deltas { get; set; } = new List<Delta>();
}
class Delta
{
public int Id { get; set; }
public string Name { get; set; }
}
class Result
{
public int AId { get; set; }
public string AName { get; set; }
public int BId { get; set; }
public string BName { get; set; }
public int CId { get; set; }
public string CName { get; set; }
public int DId { get; set; }
public string DName { get; set; }
}
Got it working as below thanks to the first answer linq selectmany flatten multiple levels
Basically had to combine .SelectMany() on the "outer" parents and .Select() on the last/inner child.
//Populate data
var alphas = new List<Alpha>();
for (int a = 1; a <= 10; a++)
{
var alpha = new Alpha() { Id = a, Name = "A" + a };
for (int b = 1; b <= 10; b++)
{
var beta = new Beta() { Id = b, Name = "B" + b };
for (int c = 1; c <= 10; c++)
{
var charlie = new Charlie() { Id = c, Name = "C" + c };
for (int d = 1; d <= 10; d++)
{
var delta = new Delta() { Id = d, Name = "D" + d };
charlie.Deltas.Add(delta);
}
beta.Charlies.Add(charlie);
}
alpha.Betas.Add(beta);
}
alphas.Add(alpha);
}
var unfilteredResults = alphas.SelectMany(a => a.Betas.SelectMany(b=> b.Charlies.SelectMany(c=> c.Deltas.Select(d => new Result
{
AId = a.Id,
AName = a.Name,
BId = b.Id,
BName = b.Name,
CId = c.Id,
CName = c.Name,
DId = d.Id,
DName = d.Name
}))));
var whiteListAIds = new List<int>() { 1, 2 };
var whiteListBIds = new List<int>() { 3, 4 };
var whiteListCIds = new List<int>() { 5, 6 };
var whiteListDIds = new List<int>() { 7, 8 };
//Get results into required format with filtering
var filteredResults = unfilteredResults.Where(r => whiteListAIds.Contains(r.AId) && whiteListBIds.Contains(r.BId) && whiteListCIds.Contains(r.CId) && whiteListDIds.Contains(r.DId));
Console.WriteLine("Finished");
class Alpha
{
public int Id { get; set; }
public string Name { get; set; }
public List<Beta> Betas { get; set; } = new List<Beta>();
}
class Beta
{
public int Id { get; set; }
public string Name { get; set; }
public List<Charlie> Charlies { get; set; } = new List<Charlie>();
}
class Charlie
{
public int Id { get; set; }
public string Name { get; set; }
public List<Delta> Deltas { get; set; } = new List<Delta>();
}
class Delta
{
public int Id { get; set; }
public string Name { get; set; }
}
class Result
{
public int AId { get; set; }
public string AName { get; set; }
public int BId { get; set; }
public string BName { get; set; }
public int CId { get; set; }
public string CName { get; set; }
public int DId { get; set; }
public string DName { get; set; }
}
I want to display the last 4 articles of the last site on the main page in a concise way. I have made a model view and I only have a problem with ef core.
ViewModel:
public class ShowBlogForHomePageViewModel
{
public int BlogId { get; set; }
public string BlogTitle { get; set; }
public string BlogUrl { get; set; }
public string BlogImageName { get; set; }
public string MetaDescriptionBlog { get; set; }
}
IBlogService:
List<ShowBlogForHomePageViewModel> GetBlogPostForHome();
BlogService:
public List<ShowBlogForHomePageViewModel> GetBlogPostForHome()
{
var ListBlogs= _context.Blogs.OrderByDescending(b => new ShowBlogForHomePageViewModel()
{
BlogId = b.BlogId,
BlogImageName = b.BlogImageName,
BlogTitle = b.BlogTitle,
MetaDescriptionBlog = b.MetaDescriptionBlog,
BlogUrl = b.BlogUrl
}).Take(4).ToList();
return null;
}
I think this part is true . please check it:
public List<ShowBlogForHomePageViewModel> GetBlogPostForHome()
{
return _context.Blogs.OrderBy(b=>b.BlogId).Select(b => new ShowBlogForHomePageViewModel()
{
BlogId = b.BlogId,
BlogImageName = b.BlogImageName,
BlogTitle = b.BlogTitle,
MetaDescriptionBlog = b.MetaDescriptionBlog,
BlogUrl = b.BlogTitle
}).TakeLast(4).ToList();
}
try this
public List<ShowBlogForHomePageViewModel> GetBlogPostForHome()
{
return _context.Blogs
.OrderByDescending(b => b.BlogId)
.Select(b => new ShowBlogForHomePageViewModel
{
BlogId = b.BlogId,
BlogImageName = b.BlogImageName,
BlogTitle = b.BlogTitle,
MetaDescriptionBlog = b.MetaDescriptionBlog,
BlogUrl = b.BlogUrl
}).Take(4)
.ToList();
}
I donĀ“t know where is the mistake why it says that does not contain a defintion of ImporteSolicitado, interesesDemora and importeReintegro when they are colums of c and the last one of d
var importes = (from c in _context.ReintegroSolicitado
join d in _context.ReintegroRecibido on c.Expediente.ID equals d.Expediente.ID
group new {c,d} by new { c.Expediente.Codigo} into cd
select new { ImporteSolictadoFinal = cd.Sum(b => b.ImporteSolicitado + b.InteresesDemora), ImporteReintegroFinal = cd.Sum(e => e.ImporteReintegro) });
your group element contains two property c and d. So you need refer to
this property as
...
select new {
ImporteSolictadoFinal = cd.Sum(b => b.c.ImporteSolicitado + b.c.InteresesDemora),
ImporteReintegroFinal = cd.Sum(e => e.d.ImporteReintegro) }
...
This is very tough to get right with query posted. I did my best, but it is probably not exactly correct.
var importes = (from c in _context.reintegroSolicitado
join d in _context.reintegroRecibido on c.expediente.ID equals d.expediente.ID
select new { reintegroSolicitado = c, reintegroRecibido = c})
.GroupBy(x => new { c = x.reintegroSolicitado , d = x.reintegroRecibido})
.Select(cd => new { ImporteSolictadoFinal = cd.Sum(b => b.reintegroSolicitado.ImporteSolicitado + b.reintegroSolicitado.InteresesDemora), ImporteReintegroFinal = cd.Sum(e => e.reintegroRecibido.ImporteReintegro) });
}
}
public class Context
{
public List<ReintegroSolicitado> reintegroSolicitado { get; set; }
public List<ReintegroSolicitado> reintegroRecibido { get; set; }
public Expediente expediente { get; set; }
}
public class ReintegroSolicitado
{
public Expediente expediente { get; set; }
public int ImporteSolicitado { get; set; }
public int InteresesDemora { get; set; }
public int ImporteReintegro { get; set; }
}
public class Expediente
{
public int ID { get; set; }
public int Codigo { get; set; }
}
Here is my how my bindings currently look:
MerchantAccountRequest request = new MerchantAccountRequest
{
Individual = new IndividualRequest
{
FirstName = merchant.MerchantIndividual.FirstName,
LastName = merchant.MerchantIndividual.LastName,
Email = merchant.MerchantIndividual.Email,
Phone = merchant.MerchantIndividual.Phone,
DateOfBirth = merchant.MerchantIndividual.DateOfBirth,
Ssn = merchant.MerchantIndividual.Ssn,
Address = new AddressRequest
{
StreetAddress = merchant.MerchantIndividual.StreetAddress,
Locality = merchant.MerchantIndividual.Locality,
Region = merchant.MerchantIndividual.Region,
PostalCode = merchant.MerchantIndividual.PostalCode
}
},
Business = new BusinessRequest
{
LegalName = merchant.MerchantBusiness.LegalName,
DbaName = merchant.MerchantBusiness.DbaName,
TaxId = merchant.MerchantBusiness.TaxId,
Address = new AddressRequest
{
StreetAddress = merchant.MerchantBusiness.StreetAddress,
Locality = merchant.MerchantBusiness.Locality,
Region = merchant.MerchantBusiness.Region,
PostalCode = merchant.MerchantBusiness.PostalCode
}
},
Funding = new FundingRequest
{
Descriptor = merchant.MerchantFunding.Descriptor,
Destination = FundingDestination.BANK,
Email = merchant.MerchantFunding.Email,
MobilePhone = merchant.MerchantFunding.MobilePhone,
AccountNumber = merchant.MerchantFunding.AccountNumber,
RoutingNumber = merchant.MerchantFunding.RoutingNumber
},
TosAccepted = merchant.TosAccepted,
MasterMerchantAccountId = merchant.MasterMerchantAccountId,
Id = merchant.MerchantId
};
And I need to use AutoMapper to achieve the above.
This is what I've tried:
CreateMapperProfile
EDIT:
CreateMap<Classes.Merchant, MerchantAccountRequest>()
.ForMember(dest => dest.Individual, source => source.MapFrom(s => s.MerchantIndividual))
.ForMember(dest => dest.Business, source => source.MapFrom(s => s.MerchantBusiness))
.ForMember(dest => dest.Funding, source => source.MapFrom(s => s.MerchantFunding))
.ForMember(dest => dest.Id, source => source.MapFrom(s => s.MerchantId));
Here is the Merchant class:
public partial class Merchant :
{
public int Id { get; set; }
public string MerchantId { get; set; }
public virtual MerchantIndividual MerchantIndividual { get; set; }
public virtual MerchantBusiness MerchantBusiness { get; set; }
public virtual MerchantFunding MerchantFunding { get; set; }
public bool TosAccepted { get; set; }
public string MasterMerchantAccountId { get; set; }
public bool isSubMerchant { get; set; }
}
And the mappings;
EDIT:
MerchantAccountRequest request = _mapper.Map<MerchantAccountRequest>(merchant);
request.Individual = _mapper.Map<IndividualRequest>(merchant.MerchantIndividual);
request.Business = _mapper.Map<BusinessRequest>(merchant.MerchantBusiness);
request.Funding = _mapper.Map<FundingRequest>(merchant.MerchantFunding);
Can the first line of code MerchantAccountRequest request = _mapper.Map<MerchantAccountRequest>(merchant); above do all the mapings?
..
..
..
..
How can I create the correct mappings?
You don't need to call _mapper.Map on the properties of the request.
Just call MerchantAccountRequest request = _mapper.Map<MerchantAccountRequest>(merchant); and assuming you have a map for each type you should be fine.
I think something along the lines of the following should get you going down the right path.
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Merchant, MerchantAccountRequest>()
.ForMember(dest => dest.Individual, c => c.MapFrom(source => source.MerchantIndividual));
cfg.CreateMap<MerchantIndividual, IndividualRequest>();
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
var merchant = new Merchant
{
Id = 1,
MerchantIndividual = new MerchantIndividual { FirstName = "John Doe" }
};
var merchantAccountRequest = mapper.Map<Merchant, MerchantAccountRequest>(merchant);
}
}
public class Merchant
{
public int Id { get; set; }
public MerchantIndividual MerchantIndividual { get; set; }
}
public class MerchantIndividual
{
public string FirstName { get; set; }
}
public class MerchantAccountRequest
{
public int Id { get; set; }
public IndividualRequest Individual { get; set; }
}
public class IndividualRequest
{
public string FirstName { get; set; }
}
MenuSetup and AccessRules have a one to many relation as described below.
public class MenuSetup
{
public virtual int MenuId { get; set; }
public virtual string DisplayText { get; set; }
public virtual int MenuOrder { get; set; }
public virtual bool MenuStatus { get; set; }
public virtual bool HasKids { get; set; }
public virtual IList<MenuAccessRules> AccessRules { get; set; }
}
public class MenuAccessRules
{
public virtual int Id { get; set; }
public virtual Boolean CanCreate { get; set; }
public virtual Boolean CanUpdate { get; set; }
public virtual Boolean CanDelete { get; set; }
public virtual FamsRoles Roles { get; set; }
public virtual MenuSetup Menu { get; set; }
}
I want to project the result of the query below in a view model
var result = session.QueryOver<MenuSetup>()
.Where(p => p.MenuId == id)
.List();
var vs = result.SelectMany(x => x.AccessRules, (a, b) => new MenuDetailsViewModel
{
MenuId = a.MenuId,
DisplayText = a.DisplayText,
MenuOrder = a.MenuOrder,
HasKids = a.HasKids,
MenuStatus = a.MenuStatus,
AccessRuleLists = a.AccessRules.
Select(c => new AccessRulesList {
Id = b.Id,
MenuId = b.Menu.MenuId,
RoleId = b.Roles.RoleId,
CanCreate = b.CanCreate,
CanUpdate = b.CanUpdate,
CanDelete = b.CanDelete }).ToList()
}).SingleOrDefault();
When AccessRules has data, vs returns MenuDetailsViewModel, but when AccessRules is Empty vs returns null.
Please how do i craft my selectMany to return MenuDetailsViewModel irrespective of AccessRules data.
Thanks in advance for your help
Would something like this:
var vs = result.Select(x => new MenuDetailsViewModel
{
MenuId = x.MenuId,
DisplayText = x.DisplayText,
MenuOrder = x.MenuOrder,
HasKids = x.HasKids,
MenuStatus = x.MenuStatus,
AccessRuleLists = x.AccessRules == null ? null : x.AccessRules.
Select(c => new AccessRulesList
{
Id = c.Id,
MenuId = c.Menu.MenuId,
RoleId = c.Roles.RoleId,
CanCreate = c.CanCreate,
CanUpdate = c.CanUpdate,
CanDelete = c.CanDelete
}).ToList()
}).SingleOrDefault();
Check below code it may help
var vs = result.SkipWhile(a=> a.AccessRules==null).SelectMany(x => x.AccessRules, (a, b) => new MenuDetailsViewModel
{
MenuId = a.MenuId,
DisplayText = a.DisplayText,
MenuOrder = a.MenuOrder,
HasKids = a.HasKids,
MenuStatus = a.MenuStatus,
AccessRuleLists = a.AccessRules.
Select(c => new AccessRulesList {
Id = b.Id,
MenuId = b.Menu.MenuId,
RoleId = b.Roles.RoleId,
CanCreate = b.CanCreate,
CanUpdate = b.CanUpdate,
CanDelete = b.CanDelete }).ToList()
}).SingleOrDefault();