Our table structure looks like below:
appointmentID
1abc --------------->1
1abc (latest) ------------>2
1hjt
990aa
990aa
990aa (latest
DateTime start = DateTime.Now.AddDays(0);
DateTime end = DateTime.Now.AddDays(7));
List<JobCustomers> appointments = objectContext.JobCustomers.Where(
a => a.StartTime >= start && a.EndTime <= end && !string.IsNullOrEmpty(a.AppointmentId)).ToList();
foreach (JobCustomers appointmentItem in appointments) {
// HERE I WANT TO WRITE SOME CODE
-- WHEN WE ARE INSERTING NEW RECORD OF A SAME ID EX "1abc" IT MUST
COMPARE WITH LATEST RECORD "-----2>
}
My requirement: if there are morethan 1 rows with same id then I need to bring latest record by appointment id something like below
List<JobCustomers> appointments = objectContext.JobCustomers.Where(
a => a.StartTime >= start && a.EndTime <= end && !string.IsNullOrEmpty(a.AppointmentId).**take(0**)).ToList();
In simple words : Using LINQ when we are inserting a new record with same id we need to compare with a last inserted record
Neither LINQ nor SQL don't know in which order you insert data, you need to have an extra field to save this order (could be a date, or an autonumeric). Once you have that, you will be able to use:
YourList.OrderBy(i => i.Id).ThenByDescending(i => i.YourColumnToSaveOrder)
var latestAppts = appointments.GroupBy(x => x.AppointmentId)
.Select(g => g.Last());
If I'm reading this correctly, you're trying to specifically grab the latest record with the same ID that's being brought That would simply need to be done with LINQ's LastOrDefault extension method:
//Variable 'yourNewRecord' is what you're about to enter into the database
var latestAppt = objectContext.JobCustomers
.LastOrDefault(a => a.StartTime >= start &&
a.EndTime <= end &&
a.AppointmentID.Equals(yourNewRecord.AppointmentID)
EDIT: For more information about LastOrDefault, please look at the MSDN link here.
Related
I'm trying to create a table using react-table that would display data that matches today's date as the top result. For instance, today is 18 August 2021, so I would like any data entry that matches 08/18/2021 (mm/dd/yyyy format) to be displayed as the topmost entry in my table.
My current table looks like this
To give an example, I have already sorted my table in chronological order (from earliest to latest in mm/dd/yyyy format). However, I want any entry/entries in the table above with today's date (eg. Date of Operation: 08/18/2021) to be displayed at the top of the table. Thereafter, entries that do not match today's date will continue to be sorted in chronological order.
Can someone please let me know how this can be done? Thank you.
Without getting into the code details, you should be able to do this by supplying a custom sort function in the column definition API docs. We don't do this specific sort but we do have multiple custom sort functions, and I got the most help in writing them by reading the sortTypes.js file from the library source.
Here's a simple date sort function. You basically get two rows and a columnId and return -1, 0, or 1.
const prevDate = new Date(prev.original[columnId])
const prevIsDate = ...
const currDate = new Date(curr.original[columnId])
const currIsDate = ...
if (prevIsDate && currIsDate) {
return prevDate > currDate ? 1 : -1
} else {
if (!prevIsDate) {
return !currIsDate ? 0 : 1
} else {
return 1
}
}
}
I am using ASP.NET MVC, EF and SQL Server 2014.
I want to generate a view which would show total sick leave and annual leave an employee with employee id. I found a LINQ query very complicated and I don't know how to use it in Asp.net MVC. I wrote a controller for this purpose and now I have no idea how to display this data in the view.
Please help me with this. If there is better way of doing this or if I am making mistakes, please let me know.
SQL queries are below:
SELECT
[EmployeeId], SUM(AssignedLeaveDay) AS Total_Annual_Leave
FROM
AssignLeaves
WHERE
[EmployeeId] = 1 AND LeaveTypeId = 4
GROUP BY
[EmployeeId]
SELECT
[EmployeeId], SUM(AssignedLeaveDay) AS Total_Sick_Leave
FROM
AssignLeaves
WHERE
[EmployeeId] = 1 AND LeaveTypeId = 5
GROUP BY
[EmployeeId]
enter image description here
//Controller side
var Data = from data in AssignLeaves.Where(s => s.EmployeeId == 1 && s.LeaveTypeId == 4)
group data by data.EmployeeId into g
select new
{
EmployeeId = g.Key,
Total_Annual_Leave = g.Sum(x => x.AssignedLeaveDay)
};
var SickLeaveData = from data in AssignLeaves.Where(s => s.EmployeeId == 1 && s.LeaveTypeId == 5)
group data by data.EmployeeId into g
select new
{
EmployeeId = g.Key,
Total_Sick_Leave = g.Sum(x =>
x.AssignedLeaveDay)
};
You get Total Annual leave by: Data.FirstOrDefault().Total_Annual_Leave ;
You get Total_Sick_Leave by: SickLeaveData.FirstOrDefault().Total_Sick_Leave;
I'm getting strange results using trying to do a simple query against a date column using Linq and EF Core.
If I run the query using a date from a list of DateTime I get no results. If I substitute DateTime.Now and add a negative number of days so that if matches the date in the list of DateTimes then the query returns results as expected.
So what is the difference between DateTime.Now and another DateTime object?
In practice, why would this work (rewinding now by 30 days in the first example gives the same date as datesToCheck[0] in the second):
var reports = from r
in db.DailyReports
.Where(r => r.UserId.Equals(currentuser.Identity.Name)
&& r.Date > DateTime.Now.AddDays(-30))
select r;
But not this:
var reports = from r
in db.DailyReports
.Where(r => r.UserId.Equals(currentuser.Identity.Name)
&& r.Date > datesToCheck[0])
select r;
The database is SQL Server 2017, the column is a non-nullable smalldatetime
The datesToCheck list is generated thus:
var datesToCheck = new List<DateTime>();
var startDate = DateTime.Now;
//get Monday date three weeks ago
if (DateTime.Now.DayOfWeek != DayOfWeek.Monday)
{
while (startDate.DayOfWeek != DayOfWeek.Monday)
{
startDate = startDate.AddDays(-1);
}
}
startDate = startDate.AddDays(-21);
while (startDate < DateTime.Now)
{
if (startDate.DayOfWeek != DayOfWeek.Saturday || startDate.DayOfWeek != DayOfWeek.Sunday)
{
datesToCheck.Add(startDate);
startDate = startDate.AddDays(1);
}
}
The same behavior exists in EF6 and, as far as I know, all versions of EF. Basically, the compiler isn't clever enough to decide if datesToCheck[0] should be evaluated or converted to SQL. The query will work if you store the value in a variable and then use the variable in the LINQ query. See also: Why can't we use arrays in Entity Framework queries?
You probably have some datatype issue, Try:
DateTime datesToCheck = DateTime.Now.AddDays(-30);
var reports = from r
in db.DailyReports
.Where(r => r.UserId.Equals(currentuser.Identity.Name)
&& r.Date > datesToCheck )
select r;
I have 2 entities Documents(Id,Number,Content,Date_Added) and Adocuments(archives of documents)(Ida,Number,Content,Date_Added) and I want to move the Documents (for example) from march in my archive entity. My tables have the same fields.
Select part
WPF_TestEntities WPFModel;
DateTime init_per = new DateTime(2012, 03, 01);
DateTime fina_per = new DateTime(2012, 03, 31);
var qry = from d in WPFModel.Document // qry - documents form march
where d.Date_Added >= init_per && d.Date_Added <= fina_per
select d;
Insert part
//WPFModel.Adocument.Insert/Add(qry);
After that I can delete the march documents from the Document entity.
How can I move the data(qry) from Documents to Adocuments? (will there be any problems with the uniqueness of my Id ?)
you can try this :
WPF_TestEntities WPFModel;
DateTime init_per = new DateTime(2012, 03, 01);
DateTime fina_per = new DateTime(2012, 03, 31);
var qry = from d in WPFModel.Document // qry - documents form march
where d.Date_Added >= init_per && d.Date_Added <= fina_per
select d;
foreach (Document doc in qryluna)
{
Adocument newadoc = new Adocument();
newadoc.IdA = doc.Id;
newadoc.Nr_intern = doc.Nr_intern;
newadoc.Obiect = doc.Obiect;
newadoc.Data_Added = doc.Data_Added ;
WPFModel.Adocument.AddObject(newadoc);
WPFModel.Document.DeleteObject(doc);
}
WPFModel.SaveChanges();
you can do trying downcasting the element result from query, if it will not run you should take each element and copy to a new bject, than you can save it in hystory table.
The id could be a problem, because if you settled the id as autoincrement (identity on sql server) of course the db will try to release a new id, instead your old one.
The most secure task that you should do is to questy the first entity, take each values and fill a new hystorical entity (related to the hystory table) and save it.
I guess that you could have the second table (Adocuments) with those fields:
id (your table identity id)
ida (your id copied from Documents table, to really maintain the history)
number
content
date_added
I hope this is useful for you :)
I have two tables
TableA (articles)
int id
int Type
string name
and
TableB (compatibles)
int linked_ID
int tableA_ID
TableA records:
id=1, Type=0, name="ArticleA"
id=2, Type=1, name="ArticleB"
id=3, Type=2, name="ArticleC"
id=4, Type=1, name="ArticleD"
TableB records:
linked_ID= 1, tableA_ID=2
linked_ID= 1, tableA_ID=3
linked_ID= 1, tableA_ID=4
TableB has a list of arcicels that are compatible to a certain article. I am quite new to queries (didn't need them in my projects yet). But as C# and WPF allow some pretty cool automation with Binding I would like to add a binding that returns the following:
Give me all articles that are of Type 1 and compatible to my selected article (id=1).
The simple part of it works well (articles has a list of all articles):
private ObservableCollection<Article> _articles =
new ObservableCollection<Article>();
[fill it with the available articles]
and then:
comboBoxArticles.ItemsSource =
_articles.AsBindable().Where( c => c.Typ == 0 );
How can I extend the Where clause to query another table?
Thanks a lot in advance.
It appears as if you want to "join" two "tables" using Linq. Here is something to get you started:
comboBoxArticles.ItemsSource =
from article in _articles
from compatible in _compatibles
where article.Type == 0 && && article.id == compatible.tableA_ID && compatible.linked_ID == 1
select article;
... or in method chain...
comboBoxArticles.ItemsSource = _articles
.SelectMany(article => _compatibles, (article, compatible) => new {article, compatible})
.Where(#t => #t.article.Type == 0 && #t.article.id == #t.compatible.tableA_ID && #t.compatible.linked_ID == 1)
.Select(#t => #t.article);