Is this even possible? It seems like I should be able to.
This is my issue. I need to run a web service method from a 3rd party to get a collection of available items where I need the ID and a Status property. Then I have method using LINQ to SQL that retrieves the items that are current.
What I need to do is retrieve the items that are current and available. I can connect them through ID BUT I also need the Status returned from the web service method.
Ideally, my final results will be the same results as from the LINQ to SQL method plus the Status property from the web service method.
Any assistance would be appreciated. Thanks!
Below is what I want to do. Have a method that takes in the list of objects from the web service and join with the existing query.
public List<Items> GetItems(List<AvailableItems> availList)
{
var result = (from c in dataContext.items
where c.status == "current"
select c;
return result;
}
public List<Item> GetItems(List<AvailableItems> availList)
{
var result = (from c in dataContext.items.AsEnumerable())
join a in availList on a.id equals c.id
where c.status == "current"
select c;
return result.ToList();
}
Re-Edit:
I typically extract the ids as a lookup list, and do the following:
public List<Items> GetItems(List<AvailableItems> availList)
{
var availableItemIds = availList.Select(a => a.Id).ToList();
var items = (from item in dataContext.items
where availableItemIds.Contains(item.Id)
where item.status == "current"
return items;
}
Related
I have to created filters data in spring boot. From frontEnd, I am sending a list containing the selected id of each category.I need to return items based on this list. I can do it this way
Service:
public List<ProductModel> getProductFilter(Integer[] categories) {
int size = categories.length;
if(size == 1){
return productRepository.getProductFilteredByOneCategory(Long.valueOf(categories[0]));
}else {
return productRepository.getProductFilteredByTwoCategory(Long.valueOf(categories[0]),Long.valueOf(categories[1]));
}
}
}
Repository:
#Query("SELECT c FROM ProductModel c WHERE c.categoryModel.id = :Category_id")
List<ProductModel> getProductFilteredByOneCategory(Long Category_id);
#Query("SELECT c FROM ProductModel c WHERE c.categoryModel.id = :Category_idOne OR c.categoryModel.id = :Category_idTwo")
List<ProductModel> getProductFilteredByTwoCategory(Long Category_idOne, Long Category_idTwo);
But if there are 50 of these categories, it is useless. Can anyone tell me how to make it better? There is some way to generate a query from a list?
You can use in instead of using multiple or operations as follows. It select all productModels match any categoryModel id in List.
#Query("SELECT c FROM ProductModel c WHERE c.categoryModel.id in category_ids")
List<ProductModel> getProductFilteredByCategoryIds(List<Long> Category_ids);
As #YJR said, IN clause is the solution, but you should also consider declaring query method as shown below, which doesn't require writing JPQL.
public List<ProductModel> findByCategoryModel_IdIn(List<Long> categoryIds);
Is this a correct way of retreiving data from database using linq?
var c= using db in db.c where c.id==id
Is this a correct way of retreiving data from database using linq?
partially yes.
It's better to write your query inside a method like this:
public static Product GetProduct(int id, string name)
{
DBNameDataContext myDB = new DBNameDataContext();
var product = from p in myDB.Products
where p.ID == id
&& p.Name == name
select p;
return product;
}
and then in your main code you can get your Product as below:
var product = GetProduct(5, "C# in Depth");
(Sample code is in C#)
I'm using fluent nhibernate
And I want load some record from the table:
public IQueryable<T> Load()
{
return Session.Query<T>();
}
public IQueryable<T> Load(Expression<System.Func<T, bool>> expression)
{
return Load().Where(expression);
}
usage:
var list = repository.Load(a=> a.Id > 1000);
in case of huge table count of list is huge too, but I wont only first (top) 100 (for example) records.
var list = repository.Load(a=> a.Id > 1000).Take(100);
Question: who to load top 100 records (using my id expression), but not loading all record (after 1100)?
I think you yourself have given the answer there, which is
var list = repository.Load(a=> a.Id > 1000).Take(100);
Take(100) would perfectly suffice your need. If your requirement is something else then specify with more clarity.
I have a webservice I call from a WP7 app. I get a list of high scores in a table (name/score).. What is the simpliest way to add a 3rd column on the far left which is simply the row?
Do I need to add a property to the entity? Is there someway to get the row #?
I tried these things below with no success..
[OperationContract]
public List<DMHighScore> GetScores()
{
using (var db = new DMModelContainer())
{
// return db.DMHighScores.ToList();
var collOrderedHighScoreItem = (from o in db.DMHighScores
orderby o.UserScore ascending
select new
{
o.UserName,
o.UserScore
}).Take(20);
var collOrderedHighScoreItem2 = collOrderedHighScoreItem.AsEnumerable().Select((x, i) => new DMHighScoreDTO
{
UserName = x.UserName,
UserScore = x.UserScore
}).ToList();
}
}
[DataContract]
public class DMHighScoreDTO
{
int Rank;
string UserName;
string UserScore;
}
So lets assume you want to load top 100 users in leaderboard and you want to have their rank included:
[OperationContract]
public List<ScoreDto> GetTop100()
{
// Linq to entities query
var query = (from u from context.Users
order by u.Score
select new
{
u.Name,
u.Score
}).Take(100);
// Linq to objects query from working on 100 records loaded from DB
// Select with index doesn't work in linq to entities
var data = query.AsEnumerable().Select((x, i) => new ScoreDto
{
Rank = i + 1,
Name = x.Name,
Score = x.Score
}).ToList();
return data;
}
what will the row number be used for? if this is for ordering might I suggest adding a column named Order, then map the column to your entity.
if you require a row index, you could also call the .ToList() on the query and fetch the index locations for each entity.
Edit:
you could add the Rank property and set it to Ignore. This will enable you to go through the collection set the rank with a simple for loop. This will also not be persisted in the database. It will also not have any required columns in the database.
It does add an extra iteration.
the other way to go about it. This would be to add the rank number in the generated UI and not in the data collection being used to bind.
I am using the System.Linq.Data library provided here - http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
I have the following query which works great and returns an Iqueryable
IQueryable customer =
ctx.Customers.Where(cust => true).Select("new("Name,Address")");
However, how do I access these returned columns? I cannot access them using a lambda expression as follows:
var test = customer.Where(cust=>cust.Name == "Mike").First();
"cust.Name" in the above case cannot be resolved. It does not exist in the list of methods/properties for "cust".
Am i assuming something wrong here. I understand that I am working with an anonymous type. Do I have to create a DTO in this case?
For any IQueryable you have property called ElementType.
You can use it to get the properties as explained below
IQueryable query = from t in db.Cities
selec new
{
Id = t.Id,
CityName = t.Name
};
if(query!=null)
{
Type elementType = query.ElementType;
foreach(PropertyInfo pi in elementType.GetProperties())
{
}
}
Try foreach loop:
var a = _context.SENDERS.Select(x=>new { Address=x.ADDRESS, Company=x.COMPANY });
foreach(var obj in a)
{
Console.WriteLine(obj.Address);
Console.WriteLine(obj.Company);
}