How can I fill a list field using EF and linq of this model
public class Infraccion
{
public int IdInfraccion { get; set; }
public string Serie { get; set; }
public int Numero { get; set; }
public Direccion Direccion { get; set; }
public string Comentario { get; set; }
public DateTime Fecha { get; set; }
public DateTime Hora { get; set; }
public string Dominio { get; set; }
public List<Contravencion> ListaDeContravenciones = new List<Contravencion>();
}
I DO know how to fill simple propertires, but dunno how to fill field List object where Contravencion is define like
public class Contravencion
{
public string Articulo { get; set; }
public string Inciso { get; set; }
public int IdContravencion { get; set; }
public string Descripcion { get; set; }
public int UfijasMinimo { get; set; }
public int UfijasMaximo { get; set; }
}
So far this is what I have
var listadoInfracciones = (from u in _context.Usuario
join ui in _context.UsuarioInfracciones on u.UsuarioId equals ui.UserId
join i in _context.Infraccion on ui.InfraccionId equals i.InfraccionId
join d in _context.Direcciones on i.IdDireccion equals d.DireccionId
where ui.UserId == usuario.IdUsuario
select new Infraccion
{
Comentario = i.Comentario,
Direccion = new Direccion
{
Calle = d.Calle,
Entre1 = d.Interseccion1,
Entre2 = d.Interseccion2
},
Dominio = i.Dominio,
Fecha = i.Fecha,
Numero = i.Numero,
Serie = i.Serie,
ListaDeContravenciones = new List<Contravencion>()
}).ToList();
Where can't find the right way to fill the list of Contravenciones. Heres the DB model:
I've already seen these posts but do NOT fit my needs Easy way to fill object
How to get data from the database into objectlists fast (with entity framework)
Ok so i found a way to solve my problem. I'm pretty sure it's not the best way but i least have a result. If anyone can do this entirely with linq i certainly know would be helpful not just for me but for the entire comunity. Heres my code:
var listadoInfracciones = (from u in _context.Users
join ui in _context.User_Infraccion on u.UsuarioId equals ui.UserId
join i in _context.Infraccions on ui.InfraccionId equals i.InfraccionId
join d in _context.Direccions on i.IdDireccion equals d.DireccionId
where ui.UserId == usuario.IdUsuario
select new Infraccion
{
Comentario = i.Comentario,
Direccion = new Direccion
{
Calle = d.Calle,
Entre1 = d.Interseccion1,
Entre2 = d.Interseccion2
},
Dominio = i.Dominio,
Fecha = i.Fecha,
Numero = i.Numero,
Serie = i.Serie,
IdInfraccion = i.InfraccionId
}).ToList();
foreach (var inf in listadoInfracciones)
{
var test = (from contra in _context.Contravencions
where contra.Infraccion_Contravencion.Any(c => c.InfraccionId == inf.IdInfraccion)
select new Contravencion
{
Articulo = contra.Articulo,
Inciso = contra.Inciso,
UfijasMaximo = contra.UFijasMax,
UfijasMinimo = contra.UFijasMin,
Descripcion = contra.Descripcion,
IdContravencion = contra.ContravencionId
}).ToList();
inf.ListaDeContravenciones = test;
}
Cheers!
Related
I am working to convert the below SQL code to LINQ query for MVC. It got multiple nested joins and group by.
SELECT UnitTracts.Id,
UnitTracts.UnitId,
Leases.Id,
Leases.Lessor,
Leases.Lessee,
Leases.Alias,
Leases.LeaseDate,
Leases.GrossAcres,
IIf([Page] Is Null,[VolumeDocumentNumber],[VolumeDocumentNumber] + '/' + [Page]) AS [Vol/Pg],
Leases.Legal,
Interests.TractId,
Leases.NetAcres,
UnitTracts.AcInUnit
FROM (UnitTracts INNER JOIN (((WorkingInterestGroups INNER JOIN Interests ON WorkingInterestGroups.Id = Interests.WorkingInterestGroupId)
INNER JOIN Tracts ON Interests.TractId = Tracts.Id)
INNER JOIN Leases ON WorkingInterestGroups.LeaseId = Leases.Id)
ON UnitTracts.TractId = Tracts.Id)
LEFT JOIN AdditionalLeaseInfo ON Leases.Id = AdditionalLeaseInfo.LeaseId
where unitId = 21
GROUP BY UnitTracts.Id,
UnitTracts.UnitId,
Leases.Id,
Leases.Lessor,
Leases.Lessee,
Leases.Alias,
Leases.LeaseDate,
Leases.GrossAcres,
IIf([Page] Is Null,[VolumeDocumentNumber],[VolumeDocumentNumber] + '/' + [Page]),
Leases.Legal,
Interests.TractId,
Leases.NetAcres,
UnitTracts.AcInUnit
This the query I got but it returns less records. I tried to convert from SQL to LINQ but it did not work. I really stuck now.
var leases = (from l in db.Leases
where l.Active
join ali in db.AdditionalLeaseInfoes on l.Id equals ali.LeaseId
where ali.Active
join wig in db.WorkingInterestGroups on l.Id equals wig.LeaseId
where wig.Active
join interest in db.Interests on wig.Id equals interest.WorkingInterestGroupId
where interest.Active
join tr in db.Tracts on interest.TractId equals tr.Id
where tr.Active
join ut in db.UnitTracts on tr.Id equals ut.TractId
where ut.Active
group new { l, wig, interest, tr, ali, ut } by
new
{
Id = ut.Id,
UnitId = ut.UnitId,
LeaseId = l.Id,
Lessor = l.Lessor,
Lessee = l.Lessee,
Alias = l.Alias,
LeaseDate = l.LeaseDate,
GrossAcres = l.GrossAcres,
VolPg = l.Page == null ? l.VolumeDocumentNumber : l.VolumeDocumentNumber + "/" + l.Page,
Legal = l.Legal,
TractId = interest.TractId,
NetAcres = l.NetAcres,
AcInUnit = ut.AcInUnit
} into lease
select new LeasesViewModel
{
UnitId = lease.Key.UnitId,
TractId = lease.Key.TractId,
LeaseId = lease.Key.LeaseId,
LeaseAlias = lease.Key.Alias,
Pooling = lease.Where(x => x.l.Id == lease.Key.LeaseId).Select(x => x.l.NoPooling).FirstOrDefault() ? "No" :
lease.Where(x => x.l.Id == lease.Key.LeaseId).Select(x => x.l.Pooling).FirstOrDefault() ? "Yes" : "No Review",
Lessor = lease.Key.Lessor,
GrossAc = lease.Key.GrossAcres
}).Where(x => x.UnitId == unitId).OrderBy(x => x.TractId).ToList();
Thanks for help!!
Thanks for help!!
Thanks for help!!
Thanks for help!!
I modeled you query with classes to get syntax correct :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<WorkingInterestGroups> workingInterestGroups = new List<WorkingInterestGroups>();
List<UnitTracts> unitTracts = new List<UnitTracts>();
List<Tracts> tracts = new List<Tracts>();
List<Leases> leases = new List<Leases>();
List<AdditionalLeaseInfo> additionalLeaseInfos = new List<AdditionalLeaseInfo>();
List<Interests> interests = new List<Interests>();
var results = (from unitTract in unitTracts
join tract in tracts on unitTract.TractId equals tract.Id
join interest in interests on tract.Id equals interest.TractId
join workingInterestGroup in workingInterestGroups on interest.WorkingInterestGroupId equals workingInterestGroup.Id
join lease in leases on workingInterestGroup.LeaseId equals lease.Id
join additionalLeaseInfo in additionalLeaseInfos on lease.Id equals additionalLeaseInfo.LeaseId
where unitTract.UnitId == "21"
select new { unitTract = unitTract, tract = tract, interest = interest, workingInterestGroup = workingInterestGroup,
lease = lease, additionalLeaseInfo = additionalLeaseInfo}).ToList();
var groups = results.GroupBy(x => new
{
x.unitTract.Id,
x.unitTract.UnitId,
x.lease.Lessor,
x.lease.Lessee,
x.lease.Alias,
x.lease.LeaseDate,
x.lease.GrossAcres,
x.lease.Legal,
x.interest.TractId,
x.lease.NetAcres,
x.unitTract.AcInUnit
})
.ToList();
}
}
public class WorkingInterestGroups
{
public string Id { get; set; }
public string LeaseId { get; set; }
}
public class UnitTracts
{
public string TractId { get; set; }
public string Id { get; set; }
public string UnitId { get; set; }
public string AcInUnit { get;set;}
}
public class Tracts
{
public string Id { get; set; }
}
public class Leases
{
public string Id { get; set; }
public string Lessor { get; set; }
public string Lessee { get; set; }
public string Alias { get; set; }
public string LeaseDate { get; set; }
public string GrossAcres { get; set; }
public string Legal { get; set; }
public string NetAcres { get; set; }
}
public class AdditionalLeaseInfo
{
public string LeaseId { get; set;}
}
public class Interests
{
public string TractId { get; set; }
public string WorkingInterestGroupId { get; set; }
}
}
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.
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; }
}
I am working on an existing solution. Where I have two entities like
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public DateTime? DOB { get; set; }
private List<long> _accounts = new List<long>();
[Display(Name = "Account No")]
public List<long> Accounts
{
get { return _accounts; }
set { _accounts = value; }
}
[Display(Name = "Account No")]
public string AccountId
{
get { return string.Join(",", _accounts); }
set { _accounts = value != null ? value.Split(',').Where(s=>!string.IsNullOrWhiteSpace(s)).Select(s => Convert.ToInt64(s.Trim())).ToList() : new List<long>(); }
}
}
public class Account
{
public long Id { get; set; }
public string AccountName { get; set; }
public string AccountNo { get; set; }
}
and also have one ViewModel
public class UserAccountViewModel
{
public long AccountId { get; set; }
public string AccountNo { get; set; }
public int UserId { get; set; }
public string UserName { get; set; }
}
Now, how can I get List<UserAccountViewModel> from those entities?
var UserAccountViewModel = (from Account in list1
join UserAccountViewModel in list2
on Account .AccountNo equals UserAccountViewModel.AccountNo
select new { UserAccountViewModel }).ToList();
Hope it helps you.
Or to increase the performance as per suggestion
var query = dataContext.UserAccountViewModel
.Include(o => o.Account)
.Where(t=> t.AccountNo == t.Account.AccountNo).ToList();
If you have two lists of accnouts and users from which you want to create List, you can use:
var userAccount = (from account in list1
join user in list2
on account.Id.ToString() equals user.AccountIds
select new UserAccountViewModel
{
AccountId = account.Id,
AccountNo = account.AccountNo,
UserName = user.Name,
UserId = user.Id
}).ToList();
At last I get my answer.It's something like below example:
var users = new List<User>{
new User{Id=1 ,Name="Test1",Email="test1#ds.com",DOB=DateTime.Now,AccountId ="1"},
new User{Id=2 ,Name="Test2",Email="test2#ds.com",DOB=DateTime.Now,AccountId ="2"},
new User{Id=3 ,Name="Test3",Email="test3#ds.com",DOB=DateTime.Now,AccountId ="3,4"}
};
var accunts = new List<Account>
{
new Account {Id=1,AccountName = "A",AccountNo = "1"},
new Account {Id=2,AccountName = "B",AccountNo = "2"},
new Account {Id=3,AccountName = "C",AccountNo = "3"},
new Account {Id=4,AccountName = "D",AccountNo = "4"},
};
var userAccounts = (from u in users
from a in accunts
where u.Accounts.Contains(a.Id)
select new UserAccountViewModel
{
AccountNo = a.AccountNo,
AccountId = a.Id,
UserId = u.Id,
UserName = u.Name
}).ToList();
I have a form with four text boxes and two comboboxes ...
i am filtering the data and displaying the data in datagrid view depends upon the selection in combobox and text typed in textboxes ..
for that i have written the below code
private void btnRunreports_Click(object sender, EventArgs e)
{
int agefrom = Convert.ToInt32(cbGEFrom.Text);
int ageto = Convert.ToInt32(cbGETo.Text);
DateTime today = DateTime.Today;
DateTime max = today.AddYears(-(agefrom + 1));
DateTime min = today.AddYears(-(ageto));
string maximum = Convert.ToString(max);
string minimum = Convert.ToString(min);
string gender = "";
gender = Classes.reportmembers.ConvertGender(cbGEGendertype.Text);
var mems = Classes.reportmembers
.getallreportmembers(gender,
cbGEMembershiptype.SelectedText,
txtlastname.Text,
txtpostcode.Text,
txtcardnum.Text,
txtreference.Text,
cbGEStatustype.SelectedText,
maximum, minimum);
BindingSource bs = new BindingSource();
bs.DataSource = mems;
dgvReportMembers.DataSource = bs;
}
and this is my class reportmembers:
class ReportMebers
{
public int MemberID { get; set; }
public string Lastname { get; set; }
public string Firstname { get; set; }
public string Postcode { get; set; }
public string Reference { get; set; }
public string CardNum { get; set; }
public string IsBiometric { get; set; }
public string DOB { get; set; }
public string MShipType { get; set; }
public string StatusType { get; set; }
public string EndDate { get; set; }
}
class reportmembers
{
public static List<ReportMebers> getallreportmembers(string gender, string membershiptype, string lastname,
string postcode,string cardnum,string refernce,
string membershipstatustypesa, string maxage, string minage)
{
//CultureInfo provider = CultureInfo.InvariantCulture;
EclipseEntities eclipse = new EclipseEntities();
List<ReportMebers> reporall = new List<ReportMebers>();
var memberreport = from report in eclipse.members
join memtomship in eclipse.membertomships on report.member_Id equals memtomship.member_Id
join mshoption in eclipse.mshipoptions on memtomship.mshipOption_Id equals mshoption.mshipOption_Id
join membershiptypes in eclipse.mshiptypes on mshoption.mshipType_Id equals membershiptypes.mshipType_Id
join membershipstatustypes in eclipse.mshipstatustypes on memtomship.mshipStatusType_Id equals membershipstatustypes.mshipStatusType_Id
where report.member_Lastname.Equals(lastname)
&& report.member_CardNum.Equals(cardnum)
&& report.member_Postcode.Equals(postcode)
&& report.member_Reference.Equals(refernce)
&& report.member_Gender.Equals(gender)
&& membershiptypes.mshipType_Name.Equals(membershiptype)
&& membershipstatustypes.mshipStatusType_Name.Equals(membershipstatustypesa)
&& string.Compare(report.member_Dob,maxage) >= 0
&& string.Compare(report.member_Dob, minage)< 0
select new
{
report.member_Id,
report.member_Lastname,
report.member_Firstname,
report.member_Postcode,
report.member_Reference,
report.member_CardNum,
report.member_IsBiometric,
report.member_Dob,
membershiptypes.mshipType_Name,
membershipstatustypes.mshipStatusType_Name,
memtomship.memberToMship_EndDate
};
try
{
foreach (var membe in memberreport)
{
ReportMebers allmembersrepor = new ReportMebers();
allmembersrepor.MemberID = membe.member_Id;
allmembersrepor.Lastname = membe.member_Lastname;
allmembersrepor.Firstname = membe.member_Firstname;
allmembersrepor.Postcode = membe.member_Postcode;
allmembersrepor.Reference = membe.member_Reference;
allmembersrepor.CardNum = membe.member_CardNum;
allmembersrepor.IsBiometric = membe.member_IsBiometric;
allmembersrepor.DOB = membe.member_Dob;
allmembersrepor.MShipType = membe.mshipType_Name;
allmembersrepor.StatusType = membe.mshipStatusType_Name;
allmembersrepor.EndDate = membe.memberToMship_EndDate;
reporall.Add(allmembersrepor);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return reporall;
}
if i type robin in txtlastname the details will be displayed whoose last name is robin...
i have checked in database there is person with last name robin..
but it does not displayed in datagrid view...
would any guys pls help on this...
Many thanks In advance....
Your problem is, that you are doing an AND comparison over all fields. That means, only entries from the database are returned, that match ALL entered data! If you only enter robin as last name and nothing else, you will get no results, because all the other fields aren't matching. Change your query to include only those fields that are not empty. Something like this:
var query = from report in eclipse.members
join memtomship in eclipse.membertomships on report.member_Id equals memtomship.member_Id
join mshoption in eclipse.mshipoptions on memtomship.mshipOption_Id equals mshoption.mshipOption_Id
join membershiptypes in eclipse.mshiptypes on mshoption.mshipType_Id equals membershiptypes.mshipType_Id
join membershipstatustypes in eclipse.mshipstatustypes on memtomship.mshipStatusType_Id equals membershipstatustypes.mshipStatusType_Id;
if(!string.IsNullOrEmpty(lastname))
query = query.Where(r => r.member_Lastname == lastname);
if(!string.IsNullOrEmptry(cardnum)
query = query.Where(r => r.member_CardNum == cardnum);
// and so on for all parameters