I am new to EF and writing this to select then max record that contains the combination. Now i want to pick MAX of those records only.
public string GetMaxReportNo(string OfficeStationCombination = "")
{
InspectionReport InspectionReport= new InspectionReport();
string VelosiReportNo="";
var query = uow.InspectionReportRepository.GetQueryable().AsQueryable();
if (!string.IsNullOrEmpty(OfficeStationCombination))
{
VelosiReportNo = (string)query
.Where(x => x.VelosiReportNo.Contains(OfficeStationCombination))
.FirstOrDefault().VelosiReportNo.ToString();
}
return VelosiReportNo;
}
I tried everything to pick the max InspectionReportID record in where but nothing works
Order by the specified column (inspectionReportID) descendingly then take the first record:
VelosiReportNo = (string)query
.Where(x => x.VelosiReportNo.Contains(OfficeStationCombination))
.OrderByDesc(x => x.inspectionReportID)
.FirstOrDefault().VelosiReportNo.ToString();
Related
I have two databases, one is main and another is for add to cart.
I want to check add to cart prodid with main database prodid.
// here I get an error "data type issue" - that's why I convert to int
var db1prodid = Convert.ToInt32(db1.prod.Select(x => x.prodid).ToList());
var gg = Convert.ToInt32(db2.prod.Select(x => x.prodid).ToList().ToString());
var checkprodid = db2.prod.Where(x => gg == db1prodid ).ToList();
if you want to convert,
change your code as shown below:
var db1prodid = db1.prod.Select(x =>(int)x.prodid).ToList();
//or
var db1prodid = db1.prod.Select(x =>Convert.ToInt32(x.prodid)).ToList();
anyway, to compare two lists and return not matching items, you can do as below
var db1prodid = db1.prod.Select(x => Convert.ToInt32(x.prodid)).ToList();
var checkprodid = db2.prod.Where(x => !db1prodid.Contains(x.prodid)).ToList();
it'll return all rows in db2.prod that does not exist in db1.prod
At the same way,
var db2prodid = db2.prod.Select(x => Convert.ToInt32(x.prodid)).ToList();
var checkprodid = db1.prod.Where(x => !db1prodid.Contains(x.prodid)).ToList();
it'll return all rows in db1.prod that does not exist in db2.prod
public ActionResult Hotel_Read(string text)
{
var result = GetHotel().Where(c => c.Name.Contains(text) || c.City.Contains(text) || c.Country.Contains(text)).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
private static IEnumerable<HotelViewModel> GetHotel()
{
using (TravelAgancyEntities1 db = new TravelAgancyEntities1())
{
var query = db.Hotels
.Include(p => p.City.Country).Distinct().ToList();
return query.Select(Hotel => new HotelViewModel
{
Name = Hotel.Name,
City = Hotel.City.City_Name,
**Line 10-** Country = Hotel.City.Country.Country_Name,//!!!
});
}
}
When I run the code without line 10, it is working successfully, but when that code is run with line 10, then it's not working.
I assume your code should run properly. the only thing that makes me suspicious, is that you are trying to retrieve all Hotel table data plus 2 other table(with include)
try this :
var q = (from x in db.Hotels.Include(c => c.City).Include(c => c.City.Country)
where x.Id == 5030
select x).Distinct().ToList();
string s = q[0].City.Country.Country_Name;
Limit your select with Where clause.
You don't need Includes here because there is no application logic involved in creation of HotelViewModel instances.
Simple query:
db.Hotels.Select(h => new HotelViewModel
{
Name = h.Name,
City = h.City.City_Name,
Country = h.City.Country.Country_Name,
}).ToList();
Will return from the DB exactly the data that you need.
When you first do Includes, and then call ToList();:
var query = db.Hotels.Include(p => p.City.Select(x => x.Country))
.Distinct()
.ToList();
You fetch form DB all the Hotel properties, all the City properties and
all the Country properties while all you really need is only their names.
I have the following code to extract records from a dbcontext randomly using Guid class:
var CategoryList = {1,5};
var generatedQues = new List<Question>();
//Algorithm 1 :)
if (ColNum > 0)
{
generatedQues = db.Questions
.Where(q => CategoryList.Contains(q.CategoryId))
.OrderBy(q => Guid.NewGuid()).Take(ColNum).ToList();
}
First, I have a list of CategoryId stored in CategoryList as a condition to be fulfilled when getting records from the db. However, I would like to achieve an even distribution among the questions based on the CategoryId.
For example:
If the ColNum is 10, and the CategoryId obtained are {1,5}, I would like to achieve by getting 5 records that are from CategoryId = 1 and another set of 5 records from CategoryId = 5. If the ColNum is an odd number like 11, I would also like to achieve an even distribution as much as possible like maybe getting 5 records from CategoryId 1 and 6 records from CategoryId 2.
How do I do this?
This is a two step process,
Determine how many you want for each category
Select that many items from each category in a random order
For the first part, define a class to represent the category and how many items are required
public class CategoryLookup
{
public CategoryLookup(int catId)
{
this.CategoryId = catId;
}
public int CategoryId
{
get; private set;
}
public int RequiredAmount
{
get; private set;
}
public void Increment()
{
this.RequiredAmount++;
}
}
And then, given your inputs of the required categories and the total number of items required, work out how many are required for each category
var categoryList = new []{1,5};
var colNum = 7;
var categoryLookup = categoryList.Select(x => new CategoryLookup(x)).ToArray();
for(var i = 0;i<colNum;i++){
categoryLookup[i%categoryList.Length].Increment();
}
The second part is really easy, just use a SelectMany to get the list of questions (Ive used a straight linq to objects to test, should work fine for database query. questions in my code would just be db.Questions in yours)
var result = categoryLookup.SelectMany(
c => questions.Where(q => q.CategoryId == c.CategoryId)
.OrderBy(x => Guid.NewGuid())
.Take(c.RequiredAmount)
);
Live example: http://rextester.com/RHF33878
You could try something like this:
var CategoryList = {1,5};
var generatedQues = new List<Question>();
//Algorithm 1 :)
if (ColNum > 0 && CategoryList.Count > 0)
{
var take = // Calculate how many of each
// First category
var query = db.Questions
.Where(q => q.CategoryId == CategoryList[0])
.OrderBy(q => Guid.NewGuid()).Take(take);
// For all remaining categories
for(int i = 1; i < CategoryList.Count; i++)
{
// Calculate how many you want
take = // Calculate how many of each
// Union the questions for that category to query
query = query.Union(
query
.Where(q => q.CategoryId == CategoryList[i])
.OrderBy(q => Guid.NewGuid()).Take(take));
}
// Randomize again and execute query
generatedQues = query.OrderBy(q => Guid.NewGuid()).ToList()
}
The idea is to just get a random list for each category and add them all together. Then you randomize that again and create your list. I do not know if it will do all this on the database or in memory, but it should be database I think. The resulting SQL will look horrible though.
I need to do a query in c# to get the position of a specific id, in a table order by a date.
My table structure
IdAirport bigint
IdUser int
AddedDate datetime
Data:
2 5126 2014-10-23 14:54:32.677
2 5127 2014-10-23 14:55:32.677
1 5128 2014-10-23 14:56:32.677
2 5129 2014-10-23 14:57:32.677
For example, i need to know in which position is the IdUser=5129, in the IdAirport=2, order by AddedDate asc. (The result in this case will be 3).
Edit:
im using iQueryables like this:
AirPort airport = (for airport as context.Airport select airport).FirstOrDefault();
Thanks for your time!
Using LINQ: If you want to find the index of an element within an arbitrary order you can use OrderBy(), TakeWhile() and Count().
db.records.Where(x => x.IdAirport == airportId)
.OrderBy(x => x.AddedDate)
.TakeWhile(x => x.IdUser != userId)
.Count() + 1;
Here's a quick one :
public class test
{
public int IdAirport;
public int IdUser;
public DateTime AddedDate;
public test(int IdAirport, int IdUser, DateTime AddedDate)
{
this.IdAirport = IdAirport;
this.IdUser = IdUser;
this.AddedDate = AddedDate;
}
}
void Main()
{
List<test> tests = new List<test>()
{
new test(2, 5126, DateTime.Parse("2014-10-23 14:54:32.677")),
new test(2, 5127, DateTime.Parse("2014-10-23 14:55:32.677")),
new test(1 , 5128 , DateTime.Parse("2014-10-23 14:56:32.677")),
new test(2 , 5129 , DateTime.Parse("2014-10-23 14:57:32.677"))
};
var r = tests
.Where(t => t.IdAirport == 2)
.OrderBy(t => t.AddedDate)
.TakeWhile(t => t.IdUser != 5129)
.Count() + 1;
Console.WriteLine(r);
}
It keeps the exact order of your own list. You can modify Where/OrderBy if you wish, the interesting part is in the "TakeWhile/Count" use.
Should work fine but probably not very efficient for long lists.
edit : seems to be the same as Ian Mercer. But the "+ 1" in my own sample is needed since TakeWhile will return the number of skipped items, hence not the position of the good one. Or I didn't get well the issue.
This should do what you need:
dataTable.Rows.IndexOf(
dataTable.AsEnumerable().OrderBy(
x => x["AddedDateColumn"]).First(
x => (int)(x["IdUserColumn"]) == 5129));
I am wondering what is recommended in the following scenario:
I have a large loop that I traverse to get an ID which I then store in a database like so:
foreach (var rate in rates)
{
// get ID from rate name
Guid Id = dbContext.DifferentEntity
.Where(x => x.Name == rate.Name).FirstOrDefault();
// create new object with the newly discovered
// ID to insert into the database
dbContext.YetAnotherEntity.Add(new YetAnotherEntity
{
Id = Guid.NewGuid(),
DiffId = Id,
}
}
Would it be better/ faster to do this instead (first get all DifferentEntity IDs, rather than querying for them separately)?
List<DifferentEntity> differentEntities = dbContext.DifferentEntity;
foreach (var rate in rates)
{
// get ID from rate name
Guid Id = differentEntities
.Where(x => x.Name == rate.Name).FirstOrDefault();
// create new object with the newly discovered
// ID to insert into the database
dbContext.YetAnotherEntity.Add(new YetAnotherEntity
{
Id = Guid.NewGuid(),
DiffId = Id,
}
}
Is the difference negligible or is this something I should consider? Thanks for your advice.
Store your Rate Names in a sorted string array (string[]) instead of a List or Collection. Then use Array.BinarySearch() to make your search much faster. Rest of what I was going to write has already been written by #Felipe above.
Run them horses! There is really a lot we do not know. Is it possible to keep all the entities in memory? How many of them are duplicates with respect to Name?
A simplistic solution with one fetch from the database and usage of parallelism:
// Fetch entities
var entitiesDict = dbContext.DifferentEntity
.Distinct(EqualityComparerForNameProperty).ToDictionary(e => e.Name);
// Create the new ones real quick and divide into groups of 500
// (cause that horse wins in my environment with complex entities,
// maybe 5 000 or 50 000 fits your scenario better since they are not that complex?)
var newEnts = rates.AsParallel().Select((rate, index) => {
new {
Value = new YetAnotherEntity
{ Id = Guid.NewGuid(), DiffId = entitiesDict[rate.Name],},
Index = index
}
})
.GroupAdjacent(anon => anon.Index / 500) // integer division, and note GroupAdjacent! (not GroupBy)
.Select(group => group.Select(anon => anon.Value)); // do the select so we get the ienumerables
// Now we have to add them to the database
Parallel.ForEach(groupedEnts, ents => {
using (var db = new DBCONTEXT()) // your dbcontext
{
foreach(var ent in ents)
db.YetAnotherEntity.Add(ent);
db.SaveChanges();
}
});
In general in database scenarios, the expensive stuff is the fetch and commits, so try to keep them to a minimum.
You can decrease the number of queries you are doing in database. For example, take all names and query findind Ids where the names contains.
Try something like this.
// get all names you have in rates list...
var rateNames = rates.Select(x => x.Name).ToList();
// query all Ids you need where contains on the namesList... 1 query, 1 column (Id, I imagine)
var Ids = dbContext.DifferentEntity.Where(x => rateNames.Contains(x.Name).Select(x => x.Id).ToList();
// loop in Ids result, and add one by one
foreach(var id in Ids)
dbContext.YetAnotherEntity.Add(new YetAnotherEntity
{
Id = Guid.NewGuid(),
DiffId = id,
}