linq query with a list in the where clause - sql

I have a linq query written in the below format. Now when I am passing a consumerID it works fine and I am able to put it in the where clause. However when I try to pass a list of consumerIds, how can I put this in the where clause. I have looked through some solution online and they all use some other linq format which I dont want to use.
Please suggesest if I can have a list in the where clause, something similar to how we can have in clause in sql??
public ICollection<ConsumerExchangeChangeDto> GetByConsumers(List<int> consumerIDs)
{
EnrollmentReportingModel db = (EnrollmentReportingModel)Context.DbContext;
var results = (from ecew in db.A
join ecewe in db.B on ecew.ID
equals ecewe.ExchangeChangeEnrollmentWindowID into temp
from j in temp.DefaultIfEmpty()
join cecr in db.C on ecew.ConsumerExchangeChangeRequestID equals cecr.ID
join con in db.D on cecr.ConsumerID equals con.ID
where con.ID.Contains(consumerIDs) && !ecew.Deleted
select new E
{
ConsumerID = con.ID,
OrganizationID = con.OrganizationID,
StartDate = ecew.StartDate,
EndDate = ecew.EndDate,
Deleted = ecew.Deleted
}).ToList();
return results;
}
Here is the dto class
public class E : ILzDto
{
public int ConsumerID { get; set; }
public int OrganizationID { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool Deleted { get; set; }
}

Change this:
where con.ID.Contains(consumerIDs)
to this:
where consumerIDs.Contains(con.ID)
This will check if the id of the items in the select statement are in the input list.

Related

Issue with querying database using LINQ query to bring list of DTO

I have a LINQ query in the below format. The problem is that I am passing a list of 100 consumerID in the form of list. I want to query the database and bring result for
all these 100 consumerIds. However the query brings back the result only for the first guy. I am suspecting I am missing something in the where clause. I am sure there are matching results in the database for all these 100 consumerIds.
public ICollection<ConsumerExchangeChangeDto> GetByConsumers(List<int> consumerIDs)
{
EnrollmentReportingModel db = (EnrollmentReportingModel)Context.DbContext;
var results = (from ecew in db.A
join ecewe in db.B on ecew.ID
equals ecewe.ExchangeChangeEnrollmentWindowID into temp
from j in temp.DefaultIfEmpty()
join cecr in db.C on ecew.ConsumerExchangeChangeRequestID equals cecr.ID
join con in db.D on cecr.ConsumerID equals con.ID
where consumerIDs.Contains(con.ID) && !ecew.Deleted
select new E
{
ConsumerID = con.ID,
OrganizationID = con.OrganizationID,
StartDate = ecew.StartDate,
EndDate = ecew.EndDate,
Deleted = ecew.Deleted
}).ToList();
return results;
}
Here is the dto class
public class E : ILzDto
{
public int ConsumerID { get; set; }
public int OrganizationID { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool Deleted { get; set; }
}
I think you want Any, not contains:
public ICollection<ConsumerExchangeChangeDto> GetByConsumers(List<int> consumerIDs)
{
EnrollmentReportingModel db = (EnrollmentReportingModel)Context.DbContext;
var results = (from ecew in db.A
join ecewe in db.B on ecew.ID
equals ecewe.ExchangeChangeEnrollmentWindowID into temp
from j in temp.DefaultIfEmpty()
join cecr in db.C on ecew.ConsumerExchangeChangeRequestID equals cecr.ID
where consumerIDs.Any(x => x == cecr.ConsumerID) && !ecew.Deleted
select new E
{
ConsumerID = cecr.ConsumerID,
OrganizationID = con.OrganizationID,
StartDate = ecew.StartDate,
EndDate = ecew.EndDate,
Deleted = false
}).ToList();
return results;
}

Joining query in Linq

I have 2 tables. ProductOrder and Member.
ProductOrder: OrderId, MemberId, DateTimeUTC.
Member : MemberId, FName, LName.
I want to retun a list which content OrderId, Fname, LName, DateTimeUTC.
public List<ProductOrder> GetOrderDetails()
{
using (var db = new StoreEntities())
{
var query = (from pd in db.ProductOrder
join od in db.Member on pd.MemberId equals od.MemberId
orderby od.MemberId
select new
{
pd.OrderId,
od.FName,
od.LName,
pd.DateTimeUTC,
}).ToList();
return query;
}
}
But here some error occur.
Please help.
Your query returns a collection of anonymous type instances. It shouldn't be returned from as method.
You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type.
from Anonymous Types (C# Programming Guide)
Instead, you have to create new class to store your results:
public class OrderInfo
{
public int OrderId { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public DateTimeUTC { get; set; }
}
change method declaration to return collection of OrderInfo:
public List<OrderInfo> GetOrderDetails()
and modify query to return a collection of these objects:
var query = (from pd in db.ProductOrder
join od in db.Member on pd.MemberId equals od.MemberId
orderby od.MemberId
select new OrderInfo
{
pd.OrderId,
od.FName,
od.LName,
pd.DateTimeUTC,
}).ToList();

How to add where clause for child items in Castle ActiveRecord

I am using Castle ActiveRecord and created two entities as follow :
[ActiveRecord("Teams")]
public class Team : ActiveRecordLinqBase<Team>
{
public Team()
{
Members = new List<Member>();
}
[PrimaryKey]
public int Id { get; set; }
[Property("TeamName")]
public string Name { get; set; }
[Property]
public string Description { get; set; }
[HasMany(Inverse = true,
Lazy = true,
Cascade = ManyRelationCascadeEnum.AllDeleteOrphan)]
public virtual IList<Member> Members { get; set; }
}
[ActiveRecord("Members")]
public class Member : ActiveRecordLinqBase<Member>
{
[PrimaryKey]
public int Id { get; set; }
[Property]
public string FirstName { get; set; }
[Property]
public string Lastname { get; set; }
[Property]
public string Address { get; set; }
[BelongsTo("TeamId")]
public Team Team { get; set; }
}
And I used ICriterion to have filtered Team data
IList<ICriterion> where = new List<ICriterion>();
where.Add(Expression.Eq("Name", "name1"));
ICriterion[] criteria = where.ToArray();
var teams = Team.FindAll(criteria);
So far it works well, but I want to add another filter on Members table. The result query would be like this
select *
from Teams t join Member m on t.Id = m.TeamId
where t.Name = 'name1'
and m.Address = 'address'
How to get this done using ICriterion?
I mean how to add criterion for Team.Members property.
Not using LINQ. (I know this could be done using linq easily)
For join you can use
DetachedCriteria
DetachedCriteria criteriaTeam = DetachedCriteria.For<Team>();
DetachedCriteria criteriaMember = criteriaTeam .CreateCriteria("Members");
criteriaTeam .Add(Expression.Eq("Name", "name1"));
criteriaMember.Add(Expression.Eq("Address", "address"));
ICriteria executableCriteria = criteriaTeam .GetExecutableCriteria(session);
executableCriteria.List<Team>();
This will return only Team.To return both Team and Members in a single fetch you can use NHibernate result transformer Projections in NHibernate

PetaPoco returning incorrect ID

I have the following model and methods:
[PetaPoco.TableName("TestStep")]
[PetaPoco.PrimaryKey("ID")]
public class TestStep
{
public int ID { get; set; }
public int ParentID { get; set; }
public string Name { get; set; }
public string Details { get; set; }
}
public IEnumerable<TestStep> GetById(int ID)
{
var db = new PetaPoco.Database("TestProcedureDB");
return db.Query<TestStep>(#"SELECT * FROM TESTSTEP TS
INNER JOIN TESTSTEPLINK L ON L.STEPID = TS.ID
WHERE L.TESTID = #0", ID);
}
When the POCO is populated, the ID property value is that of the ID column in the TESTSTEPLINK table. If I change the query to return SELECT TS.* then all is ok. Is this a bug or am I missing something?
PetaPoco will go through all your return columns and map them.
First it will map Id from the table TESTSTEP, then it finds Id again and so it overrides the previously set value.
If you are doing a join like this and only want specific information, you should either only specify the columns you want to return (otherwise you are bringing back more data than needed which is a performance issue)
or do as you did to fix it by using TS.* to ensure only the columns from the first table are mapped.

NHibernate - query specific columns and return distinct records?

I am new to NH.
I have a table in a legacy DB that looks like this:
Id,
CompanyId,
Description,
[LOADS of other columns here]
I would like to return a DISTINCT set of data using NHibernate, selecting only specific columns and using a WHERE statement. The SQL would looks something like this:
SELECT DISTINCT
[table_name].CompanyId,
[table_name].Description
FROM
[table_name]
WHERE
[table_name].CompanyId = 2
Having googled this I came up with:
ProjectionList projections = Projections.ProjectionList();
projections.Add(Projections.Property("CompanyId"), "CompanyId");
projections.Add(Projections.Property("Name"), "SomeName");
var companyDto = session.QueryOver<Company>()
.Where(x => x.CompanyId == 2)
.Select(projections)
.TransformUsing(Transformers.AliasToBean<CompanyDto>())
.List<CompanyDto>();
if (companyDto != null)
Console.WriteLine(string.Format("{0}, {1}", companyDto.CompanyId, companyDto.SomeName));
Where the DTO is:
public class CompanyDto
{
public int CompanyId { get; set; }
public string SomeName { get; set; }
}
And the entity is:
public class Company
{
public virtual int Id { get; private set; }
public virtual int CompanyId { get; set; }
public virtual string Name { get; set; }
}
This does not bring back disinct records. I know that normally I would have to use a different transform (DistinctRootEntity) but I cannot use two transforms. How can I combine all of the things I want, into a single call? It must be possible, its basic SQL ....
I need to:
not use HQL
not bring back all columns for the record
not bring back duplicate rows
there is a Projection for this
var projections = Projections.Distinct(Projections.ProjectionList()
.Add(Projections.Property("CompanyId").As("CompanyId"))
.Add(Projections.Property("Name").As("SomeName"));