ViewBag select list LINQ table join - c#

Is it possible to join tables in a SelectList?
Here is what I have:
ViewBag.Clients = new SelectList(db.IPACS_Clients, "clientID", "name", 0);
I need to join the db.IPACS_Clients_Network table, I still need "clientID" but for "name" I need to be able to select IPACS_Clients.name + " - " + IPACS_Clients_Network.name
Is this possible with a Viewbag?

While this way is not recommended, I was able to find the answer.
ViewBag.Clients = new SelectList(db.IPACS_Clients_Network
.Join(
db.IPACS_Clients,
v => v.networkClientID,
s => s.networkClientID,
(v, s) =>
new
{
v = v,
s = s
}
)
.Select(
temp0 =>
new
{
v = temp0.v,
s = temp0.s
}
).Select(m => new SelectListItem
{
Value = SqlFunctions.StringConvert((double)m.s.clientID).Trim(),
Text = m.v.name + " - " + m.s.name
}), "Value", "Text", 0);

Related

Loop through 2 grouped object lists & add them in an observable collection C#

I have these two grouped object lists which I grouped like this:
var q = it
.AsQueryable()
.GroupBy(x => x.date)
.Select(g => new
{
Date = g.Key,
Details = g.Select(x => new
{
Name = x.name,
Price = x.price,
Trans = x.trans,
})
.ToList()
})
.ToList();
var q4 = t
.AsQueryable()
.GroupBy(x => x.date)
.Select(g => new
{
Date = g.Key,
Details = g.Select(x => new
{
Location = x.location,
Points = x.points,
Pos = x.position,
Time = x.time,
Discount = x._discount,
Totals = x._total,
Trans = x.trans,
Ref = x.refer
})
.ToList()
});
What I want to do is looped through these lists and add their respective contents together in a new observable collection, like this:
Transactions = new ObservableCollection<Transaction>();
Transactions.Add(new Transaction
{
Details = "Date: " + obj.Date,
TransDet = "Time: " + k.Time + " | Reference: " + k.Ref(etc),
ItemDet = obj.Name,
obj.Price,
obj.Trans,
Isvisible = false
});
The two lists use the Date as the common factor that links them - is there a way to loop through both of them and put their contents into this new observable collection underneath the key date?
Thank you!

Group 2 or more fields on mongodb on C# using Mongo Driver

I'm trying to group 3 fields "GameName", "MinBet" and "Time", if data saved on a SQLDb, I just need use WorkScope.GetAll<Game>().GroupBy(s=> new {s.GameName,s.MinBet,s.Time}) then select data to return. But this data saved on Mongo so I cant group like that.
I have try
var query1 = Mongo.GetAll<History>("history").AsQueryable().GroupBy(s=>new GroupBy( s.GameName, s.MinBet, s.Time )).Select(s => new
{
GameId = s.First().GameId,
GameName = s.Key.GameName,
MinBet = s.Key.MinBet,
Time = s.Key.Time,
TotalWin = s.Where(s => s.WinAmount == 0).Sum(s => s.BetAmount),
TotalLose = s.Sum(s => s.WinAmount),
}).ToList();
And
var query=Mongo.GetAll<History>("history")
.Aggregate()
.Group(
s=> new GroupBy
(
s.GameName,
s.MinBet,
s.Time
),
z=> new
{
Key=z.Key,
TotalWin = z.Where(s => s.WinAmount == 0).Sum(s => s.BetAmount),
TotalLose = z.Sum(s => s.WinAmount),
GameId=z.First().Fee
}
)
.Project(s=> new
{
GameId=s.GameId,
GameName=s.Key.GameName,
MinBet=s.Key.MinBet,
Time=s.Key.Time,
TotalWin=s.TotalWin,
TotalLose=s.TotalLose,
}).ToList()
;
It alaways return MongoDB.Bson.BsonSerializationException: No matching creator found.
How can I group it to have right data like SqlDb.

Execute query using LINQ or EF to fetch records from multiple tables

I've been searching for a while now. But all the solutions seems to be different than what I expect.
So this is my query in SQL:-
Select * from
(
select Name,Description Descr from CourseTbl
union all
select MainDesc Name,MainDesc Descr from CoursedescTbl
union all
select SubHeading Name,SubDesc Descr from CourseSubDesc
union all
select Name,Descr as Descr from InternTbl
)A where A.Name like '%D%' or A.Descr like '%D%'
I want to execute the above query using LINQ or EF. and return the list in Json format. So I tried many failed attempts and this is one of them:-
public JsonResult SearchDetail()
{
string SearchKey = Request.Form["SearchName"].ToString();
IEnumerable<SearchList> QueryResult;
using (EBContext db = new EBContext())
{
try
{
QueryResult =
(from x in db.Courses
select new { A = x.Name, B = x.Description })
.Concat(from y in db.CourseDesc
select new { A = y.MainHeading, B = y.MainDesc })
.Concat(from z in db.CourseSubDesc
select new { A = z.SubDesc, B = z.SubHeading })
.Concat(from w in db.Interns
select new { A = w.Name, B = w.Descr })
.ToList();
}
catch (Exception ex)
{
return new JsonResult
{
Data = ex.Message,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
return new JsonResult
{
Data = QueryResult,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
And my SearchList Class is like this:-
public class SearchList
{
public string Name { get; set; }
public string Descr { get; set; }
}
I'm not able to put the where clause in linq query which will search in all table.
I'm getting error when I assign queryresult to my ef query. It says cannot cast to Innumerable.
Thanks in Advance.
Could you explain more on the error you are getting?
Also, have you tried using .Union() in linq?
QueryResult = db.Courses.Select(x=> new { A = x.Name, B= x.Description})
.Union(db.CourseDesc.Select(y=> new {A = y.MainHeading, B = y.MainDesc })
.Union( //so on
.ToList(); //this isn't necessary
Edit: There are two ways to input where clause, either with each search, or at the end:
QueryResult = db.Courses.Where(x=>x.Name == "Name").Select(x=> new { A = x.Name, B= x.Description})
.Union(db.CourseDesc.Where(y=>y.MainHeading == "Name").Select(y=> new {A = y.MainHeading, B = y.MainDesc })
.Union( //so on
.ToList();
Or:
QueryResult = db.Courses.Where(x=>x.Name == "Name").Select(x=> new { A = x.Name, B= x.Description})
.Union(db.CourseDesc.Where(y=>y.MainHeading == "Name").Select(y=> new {A = y.MainHeading, B = y.MainDesc })
.Union( //so on
//Where can go either before or after .ToList
.Where(item=>item.A == "Name")
.ToList();
You did not say what error/exception you are getting. But your QueryResult is of type IEnumerable<SearchList> and you appear to be assigning it an enumerable of anonymous type { A, B }.
Try this:
QueryResult = (from x in db.Courses
select new SearchList { Name = x.Name, Descr = x.Description })
.Concat(...)
.ToList();
Or
QueryResult = db.Courses.Select(x => new SearchList
{ Name = x.Name, Descr = x.Description})
.Concat(...)
.ToList();
UPDATE
Your #2 issue will be fixed if you changed your select to new up a SearchList as I did above, instead of new-ing an anonymous type.
As for your issue #1, you should insert the Where() before your Select():
result1 = db.Courses
.Where(x => x.Name.Contains('D') || x.Description.Contains('D'))
.Select(x => new SearchList { Name = x.Name, Descr = x.Description});
result2 = db.CourseDesc
.Where(y => y.MainHeading.Contains('D') || y.MainDesc.Contains('D'))
.Select(y => new SearchList { Name = y.MainHeading, Descr = y.MainDesc});
result3 = db.CourseSubDesc
.Where(...)
.Select(...);
QueryResult = result1.Concat(result2).Concat(result3).ToList();
Doing Where() as part of the query on each table is important so you do not fetch all records from that table, unlike if you do the Where() after Concat(). Also note that Concat() may throw an ArgumentNullException.
Take the lists Separately and query and concat
check this example
List<string> a = new List<string>() { "a", "b", "c" };
List<string> b = new List<string>() { "ab", "bb", "cb" };
IEnumerable<SearchList> QueryResult =
a.Where(x => x.Contains("a")).Select(x => new SearchList() { Name = x, Descr = x })
.Concat(b.Where(x => x.Contains("a")).Select(x => new SearchList() { Name = x, Descr = x }));

How to use linq result input sql where in

I have a linq script
var ID = (from item in ConflictDatas.AsEnumerable()
group item by new
{
ID = item.Field<string>("ID"),
DesignArticle = item.Field<string>("DesignArticle"),
DesignNo = item.Field<string>("DesignNo"),
PatternCode = item.Field<string>("PatternCode")
} into g
where g.Count() >= 2
select new
{
g.Key.ID
}).ToList();
I want to put this result into a sql commnad.
I try:
string sqlwhere;
sqlwhere = string.Join(",", ID);
tsql = #"
Insert ConflictDesignArticle
Select * from ReadyworkData where ID in (" + sqlwhere + #") ";
After compile:
Insert ConflictDesignArticle
Select * from ReadyworkData where ID in ({ ID = SPSOS17040113 },{ ID =
SPSOS17040115 },{ ID = SPSOS17040114 })
How to modify my code. Thanks.
Thank you for Lei Yang help
var ID = (from item in ConflictDatas.AsEnumerable()
group item by new
{
ID = item.Field<string>("ID"),
DesignArticle = item.Field<string>("DesignArticle"),
DesignNo = item.Field<string>("DesignNo"),
PatternCode = item.Field<string>("PatternCode")
} into g
where g.Count() >= 2
select new
{
g.Key.ID
}).Select(x => x.ID).ToList();

How do I specify "not in" in this lambda expression?

I have a quick question becuase my brain won't work with me...
Where do I specify that I want the user_id's in 'Users' that are NOT in 'Groups' ?
db.Users.Join(db.Groups, a => a.user_id, b => b.user_id, (a, b) => new SelectListItem
{
Value = a.user_id.ToString(),
Text = a.surname + " " + a.lastname
});
The following should work (assuming that I understood your question correctly):
db.Users
.Where(x => !db.Groups.Any(y => y.user_id == x.user_id))
.Select(a => new SelectListItem
{
Value = a.user_id.ToString(),
Text = a.surname + " " + a.lastname
});
you can try something like this:
var query = from u in db.Users
where !(from g in dc.Groups
select g.user_id)
.Contains(u.user_id)
select new SelectListItem {
Value = u.user_id.ToString(),
Text = u.surname + " " + u.lastname
};
Take a look here: http://introducinglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx

Categories