combine join with String.Contains in Linq query - sql

i have the following linq query that create a left join between two tables:
var joinResultRows = from leftTable in dataSet.Tables[leftTableName].AsEnumerable()
join
rightTable in dataSet.Tables[rightTableName].AsEnumerable()
on leftTable.Field<string>(leftComparedColumnName) equals rightTable.Field<string>(rightComparedColumnName)
into leftJoinedResult
select new { leftTable, leftJoinedResult };
i want to get the rows that answer this:
the String value in the left column contains the string value in the right column.
i tried this :
var joinResultRows = from leftTable in dataSet.Tables[leftTableName].AsEnumerable()
join
rightTable in dataSet.Tables[rightTableName].AsEnumerable()
on leftTable.Field<string>(leftComparedColumnName).Contains(rightTable.Field<string>(rightComparedColumnName)) equals true
into leftJoinedResult
select new { leftTable, leftJoinedResult };
but it doesn't work cause rightTable isn't recognized in the left side of the join.
How do i create a join that results the String.Contains, do i do the contains in the 'where' clause or in the 'On' clause?

Have you tried a SelectMany?
var result =
from left in dataSet.Tables[leftTableName].AsEnumerable()
from right in dataSet.Tables[rightTableName].AsEnumerable()
where left.Field<string>(leftComparedColumnName).Contains(right.Field<string>(rightComparedColumnName))
select new { left, right };
Edit:
The following should have the desired effect:
class ContainsEqualityComparer: IEqualityComparer<string>
{
public bool Equals(string right, string left) { return left.Contains(right); }
public int GetHashCode(string obj) { return 0; }
}
var result =
dataSet.Tables[leftTableName].AsEnumerable().GroupJoin(
dataSet.Tables[rightTableName].AsEnumerable(),
left => left,
right => right,
(left, leftJoinedResult) => new { left = left, leftJoinedResult = leftJoinedResult },
new ContainsEqualityComparer());
The key comparison is run through the custom IEqualityComparer. Two rows will only be joined when GetHashCode() of left and right are the same, and Equals returns true.
Hope it helps.

I solved it by creating SelectMany (join) that the left table holds all records and the right holds null if there is no match:
var joinResultRows = from leftDataRow in dataSet.Tables[leftTableName].AsEnumerable()
from rightDataRow in dataSet.Tables[rightTableName].AsEnumerable()
.Where(rightRow =>
{
// Dont include "" string in the Contains, because "" is always contained
// in any string.
if ( String.IsNullOrEmpty(rightRow.Field<string>(rightComparedColumnName)))
return false;
return leftDataRow.Field<string>(leftComparedColumnName).Contains(rightRow.Field<string>(rightComparedColumnName));
}).DefaultIfEmpty() // Makes the right table nulls row or the match row
select new { leftDataRow, rightDataRow };
Thank you for the tip :)

Related

How to write join query with multiple column - LINQ

I have a situation where two tables should be joined with multiple columns with or condition. Here, I have a sample of sql query but i was not able to convert it into linq query.
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
This is how i have write linq query
await (from cm in Context.CustomerMaster
join li in list.PortalCustomerDetailViewModel
on new { OldNLKNo = cm.OldAcNo, NewNLKNo = cm.CustomerCode } equals new { OldNLKNo = li.OldNLKNo, NewNLKNo = li.NewNLKNo }
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
But this query doesn't returns as expected. How do I convert this sql query into linq.
Thank you
You didn't tell if list.PortalCustomerDetailViewModel is some information in the database, or in your local process. It seems that this is in your local process, your query will have to transfer it to the database (maybe that is why it is Tmp in your SQL?)
Requirement: give me all properties of a CustomerMaster for all CustomerMasters where exists at least one PortalCustomerDetailViewModel where
customerMaster.CustomerCode == portalCustomerDetailViewModel.NewNLKNo
|| customerMaster.OldAcNo == portalCustomerDetailViewModel.OldNLKNo
You can't use a normal Join, because a Join works with an AND, you want to work with OR
What you could do, is Select all CustomerMasters where there is any PortalCustomerDetailViewModel that fulfills the provided OR:
I only transfer those properties of list.PortalCustomerDetailViewModel to the database that I need to use in the OR expression:
var checkProperties = list.PortalCustomerDetailViewModel
.Select(portalCustomerDetail => new
{
NewNlkNo = portalCustomerDetail.NewNlkNo,
OldNLKNo = portalCustomerDetail.OldNLKNo,
});
var result = dbContext.CustomerMasters.Where(customerMaster =>
checkProperties.Where(checkProperty =>
customerMaster.CustomerCode == checkProperty.NewNLKNo
|| customerMaster.OldAcNo == checkProperty.OldNLKNo)).Any()))
.Select(customerMaster => new CustomerInfoViewModel
{
Id = customerMaster.Id,
Name = customerMaster.Name,
...
});
In words: from each portalCustomerDetail in list.PortalCustomerDetailViewModel, extract the properties NewNKLNo and OldNLKNo.
Then from the table of CustomerMasters, keep only those customerMasters that have at least one portalCustomerDetail with the properties as described in the OR statement.
From every remaining CustomerMasters, create one new CustomerInfoViewModel containing properties ...
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
You don't have to use the join syntax. Adding the predicates in a where clause could get the same result. Try to use the following code:
await (from cm in Context.CustomerMaster
from li in list.PortalCustomerDetailViewModel
where cm.CustomerCode == li.NewNLKNo || cm.OldAcNo = li.OldNLKNo
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
var result=_db.Customer
.groupjoin(_db.#temp ,jc=>jc.CustomerCode,c=> c.NewNLKNo,(jc,c)=>{jc,c=c.firstordefault()})
.groupjoin(_db.#temp ,jc2=>jc2.OldAcNo,c2=> c2.OldNLKNo,(jc2,c2)=>{jc2,c2=c2.firstordefault()})
.select(x=> new{
//as you want
}).distinct().tolist();

Dynamic column search in multiple tables with gorm golang

My scenario is i have a grid with search option where user can select the column and can do the search, the grid data is coming from various tables. I have attached a sample screen of grid.
User Screen
So i'm trying to create a dynamic query for search but the problem is i can able to search only in main table (schema.Robot) not in Preload tables. whenever i trying to search data data from Preload tables let say from RobotModel table that time getting below error
pq: missing FROM-clause entry for table "robot_models"
Here is my go code
func (r *RobotsRepository) GetRobotsSummary(listParams viewmodel.ListParams, companyID uint) ([]*schema.Robot, int, error) {
mrobots := []*schema.Robot{}
var count int
var order string
if listParams.SortColumn == "" {
listParams.SortColumn = "id"
listParams.SortOrder = 1
} else {
listParams.SortColumn = util.Underscore(listParams.SortColumn)
}
if listParams.SortOrder == 0 {
order = "ASC"
} else {
order = "DESC"
}
var searchQuery string
if listParams.SearchText != "" {
switch listParams.SearchColumn {
case "Robot":
listParams.SearchColumn = "name"
case "Model":
listParams.SearchColumn = "robot_models.name"
}
searchQuery = listParams.SearchColumn +" LIKE '%"+ listParams.SearchText +"%' and Company_ID = " + fmt.Sprint(companyID)
}else{
searchQuery = "Company_ID = " + fmt.Sprint(companyID)
}
orderBy := fmt.Sprintf("%s %s", listParams.SortColumn, order)
err := r.Conn.
Preload("RobotModel", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Name")
}).
Preload("Task", func(db *gorm.DB) *gorm.DB {
return db.Where("Task_Status in ('In-Progress','Pending')").Select("ID, Task_Status")
}).
Preload("CreatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Preload("UpdatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Where(searchQuery).
Order(orderBy).
Offset(listParams.PageSize * (listParams.PageNo - 1)).
Limit(listParams.PageSize).
Find(&mrobots).Error
r.Conn.Model(&schema.Robot{}).Where(searchQuery).Count(&count)
return mrobots, count, err
}
In searchQuery variable i'm storing my dynamic query.
My question is how can i search data for preload table columns
Here is the sql query which i'm trying to achieve using gorm
SELECT robots.id,robots.name,robot_models.name as
model_name,count(tasks.task_status) as task_on_hand,
robots.updated_at,users.user_name as updated_by
FROM rfm.robots as robots
left join rfm.tasks as tasks on tasks.robot_id = robots.id and
tasks.task_status in ('In-Progress','Pending')
left join rfm.robot_models as robot_models on robot_models.id =
robots.robot_model_id
left join rfm.users as users on users.id = robots.updated_by
WHERE robot_models.name::varchar like '%RNR%' and robots.deleted_at is null
GROUP BY robots.id,robot_models.name,users.user_name
ORDER BY task_on_hand DESC LIMIT 2 OFFSET 0
and sorry for bad English!
Even though you are preloading, you are still required to explicitly use joins when filtering and ordering on columns on other tables. Preloading is used to eagerly load the data to map into your models, not to join tables.
Chain on something like this:
.Joins("LEFT JOIN rfm.robot_models AS robot_models ON robot_models.id = robots.robot_model_id")
I'm not positive if you can use the AS keyword using this technique, but if not, it should be easy enough to adjust your query accordingly.

Linq to SQL include related table

Been trying for a while now, but just can't get it to work the way I want. Referring to the code snippet below, I want to include a related table to Bricks (BrickColors). As of now BrickColors are not included and is lazy loaded.
var query = (from ul in DbContext.UserLocs
join l in DbContext.Locs on ul.LocId equals l.Id
join lb in DbContext.LocBricks on l.Id equals lb.LocId
join b in DbContext.Bricks on lb.BrickId equals b.Id
join bc in DbContext.BrickColors on b.ColorId equals bc.Id
where ul.UserId == userId
group new { LocQty = ul.Quantity, LocBrickQty = lb.Quantity, Brick = b } by new { b.BrickId, b.ColorId }
into data
orderby data.Key
select new
{
Brick = data.FirstOrDefault().Brick,
Quantity = data.Sum(d => d.LocBrickQty * d.LocQty)
})
.AsNoTracking();
If I remove .AsNoTracking() the performance is quite good, because it keeps the BrickColors table in memory, but I want it to be included in the query from the start.
I have tried DbContext.Bricks.Include(b => b.BrickColorAccessor) in the query, but that doesn't work. I think my group new { } is messing something up since I don't include BrickColors there...

LINQ getting Distinct values

I know there are several questions regarding this topic. However; I cannot find one that is directly related to my problem.
I have 3tables in a DB and the PK's from those 3 tables form a composite PK in a XRef table.
I need to be able to select Distinct items based on 2 of the keys just for display on a report.
public IEnumerable<AssemblyPrograms> GetProgramAssemblies()
{
var assembliesList = (from c in eModel.Assemblies.ToList()
join d in eModel.Programs_X_Assemblies_X_Builds
on c.AssemblyID equals d.AssemblyID
join p in eModel.Programs
on d.ProgramID equals p.ProgramID
join a in eModel.AssemblyTypes
on c.AssemblyTypeID equals a.AssemblyTypeID
select new AssemblyPrograms
{
AssemblyID = c.AssemblyID
,ProgramID = d.ProgramID
,AssemblyName = c.AssemblyName
,AssemblyPrefixName = c.AssemblyPrefixName
,ProgramName = p.ProgramName
,AssemblyTypeName = a.AssemblyTypeName
,AssemblyTypeID = a.AssemblyTypeID
});
return assembliesList;
}
This is my query and what I need to pull out of the tables
In my XRef table I have AssemblyID, ProgramID and BuildID as my composite PK.
There can be a many-many relationship from AssemblyID to ProgramID. The BuildID is the key that separates them.
I need to pull Distinct AssemblyID to ProgramID relationships for my report, the BuildID can be ignored.
I have tried .Distinct() in my query and a few other things to no avail.
I would appreciate any help anyone could give me.
Thanks
How about a Distinct overload that accepts a custom equality comparer? Something like this:
class AssemblyComparer : EqualityComparer<AssemblyPrograms> {
public override bool Equals(AssemblyPrograms x, AssemblyPrograms y) {
return x.ProgramID == y.ProgramID && x.AssemblyID == y.AssemblyID;
}
public override int GetHashCode(AssemblyPrograms obj) {
return obj.ProgramID.GetHashCode() ^ obj.AssemblyID.GetHashCode();
}
}

Performing a left outer join when an nhibernate filter is applied

I am trying to perform a LEFT OUTER JOIN with nhibernate criteria. I also have a filter that gets applied to my queries.
The problem I have is the filter stops the left outer join working properly if the join result is null.
As a very simple example I want to return all the musicians, and if they are in a band then also their band
NHibernate generates the following sql
SELECT this_.Name, band2_.Name
FROM Musicians this_
left outer join [Band] band2_
on this_.BandID = band2_.ID
WHERE (band2_.IsDeleted = 0)
which won't return the musicians if they aren't in a band. What I want is something like
SELECT this_.Name, band2_.Name
FROM Musicians this_
left outer join [Band] band2_
on this_.BandID = band2_.ID
WHERE this_.ID = 4894 /* #p3 */
(band2_.ID IS NULL OR band2_.IsDeleted = 0)
Is this possible with nhibernate?
UPDATE
var projections = new[]
{
Projections.Property("Musician.Name").As("MusicianName"),
Projections.Property("Band.Name").As("BandName")
};
return this.sessionProvider.GetSession().CreateCriteria<Musician>("Musician")
.CreateCriteria("Musician.Band", "Band", JoinType.LeftOuterJoin)
.SetProjection(projections)
.Add(Restrictions.Eq("Musician.ID", parameters.MusicianId))
.SetResultTransformer(Transformers.AliasToBean<MusicianDetailsResult>())
.UniqueResult<MusicianDetailsResult>();
The filter is defined with FluentNHibernate
this.WithName(FilterName).WithCondition("IsDeleted = 0")
This is a bug in NHibernate.
I used proposed workaround and set useManyToOne on the filter to false. This property isn't currently in FluentNhibernate so I just do it in ExposeConfiguration
foreach (var key in cfg.FilterDefinitions.Keys)
{
filter = cfg.FilterDefinitions[key];
cfg.FilterDefinitions[key] = new FilterDefinition(
filter.FilterName,
filter.DefaultFilterCondition,
filter.ParameterTypes, false);
}
Firstly, this is much easier if you simply map Band to Musician as a reference:
public class MusicianDbMap : ClassMap<Musician>
{
public MusicianDbMap()
{
...
References(x => x.Band)
.Nullable()
.Not.LazyLoad(); // Or lazy load... either way
}
}
Then you can just run a simple query - here it is in Linq-2-NHibernate:
Session.Linq<Musician>()
.Where(x => x.Band == null || !x.Band.IsDeleted)
.ToList();
Secondly, I'm not sure about this statement of yours: "which won't return the musicians if they aren't in a band"... I'm not sure if that is correct. A left outer join should return all rows, regardless of whether they are in a band or not - are you sure that you haven't made an error somewhere else?