Entity Framework Core wrong format date in database but read correct - asp.net-core

I'm working on my project with ASP.NET Core 3.1 and Entity Framework Core. I have a table with a column of Date datatype:
[Column(TypeName = "Date")]
[Required]
public DateTime Date { get; set; }
Recently when I insert data in this table, date is inserted like below:
It is marvelous that when I read data from this table to show in calendar plugin, date is correct format:
This is my code for save data in database:
var dtDate = Convert.ToDateTime(date);
_db.ImPossibleReserveDates.Add(new ImPossibleReserveDate
{
Date = dtDate.Date,
InsertTime = DateTime.Now,
IsRemoved = false
});
And this code for read data:
var list = _db.ImPossibleReserveDates.Where(x => !x.IsRemoved).Select(x => new
{
date = x.Date.ToString("yyyy-MM-dd"),
TITLE = "تعطیل"
});
No matter in server or local!
Why did this happen?

check your converted date in server before save it
its seem two convert in your date

Related

Prevent Updating createdAt field each time flush entity

I'm using symfony 2 doctrine orm to update record. But each time updating record, TIMESTAMP field called createdAt value is changing ( set current date time ). How to prevent this behavior? see my code,
public function newsDetailsAction(Request $request)
{
....
$post = $this->getDoctrine()->getRepository('AdminBundle:BlogPostEntity')->findOneBy(array('postId' => $postid ));
$views = $post->getPostViews();
$post->setPostViews($views + 1);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($post);
$entityManager->flush();
...
}
My Bad. I was using timestamp for type. That's the issue.

Assigning Value to Bootstrap-datetimepicker with Format MM/YYYY Displays Incorrect Year

I am using bootstrap-datetimepicker version 4.17.47 in ASP MVC 4 app.
I have this model property:
public DateTime MonthYear { get; set; }
I assign default value in controller (arbitrary value is just an example actual value is determined through some logic):
model.MonthYear = new DateTime(2017, 3, 1);
I display this in view using datepicker so users can update the value as needed:
#Html.TextBoxFor(model => model.MonthYear, new { #class = "form-control input month-picker" })
Script:
$('.month-picker').datetimepicker({
format: 'MM/YYYY',
useCurrent: false,
toolbarPlacement: 'bottom',
viewMode: 'months'
});
The problem is the control displays "03/0001" instead of "03/2017".
What am I missing here?
Apparently the problem is that the input is being filled with a DD/MM/YYYY date from server when datetimepicker is expecting only MM/YYYY. Try formating the textbox, like:
#Html.TextBoxFor(model => model.MonthYear, "{0:MM/yyyy}", new { #class = "form-control input month-picker" })
That should work.

Get data from sql server to appear on Kendo Scheduler

I want to know how I can get the information that I have on a sql table into a Kendo scheduler. What I currently have in the server is the Start, End, StartTimeZone, EndTimeZone, Description, Title... etc. All the stuff you need for Kendo Scheduler, but I have many events that I need to make and put into a calendar format and the scheduler seems like the best way to do it. Right now my calendar view looks like this
#(Html.Kendo().Scheduler<**censored**.Models.LeaveRequest>()
.Name("scheduler")
.Date(new DateTime(2013, 6, 13))
.StartTime(new DateTime(2013, 6, 13, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView();
views.MonthView(MonthView => MonthView.Selected(true));
})
.Timezone("Etc/UTC")
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.LeaveRequestId);
m.Field(f => f.Title).DefaultValue("No title");
m.Field(f => f.EmployeeId).DefaultValue(1);
m.Field(f => f.Title).DefaultValue("No title");
m.RecurrenceId(f => f.LeaveRequestId);
})
.ServerOperation(true)
.Read(read => read.Action("Read", "Home").Data("getAdditionalData"))
.Create("Create", "Home")
.Destroy("Destroy", "Home")
.Update("Update", "Home")
)
)
<script>
function getAdditionalData() {
var scheduler = $("#scheduler").data("kendoScheduler");
var timezone = scheduler.options.timezone;
var startDate = kendo.timezone.convert(scheduler.view().startDate(), timezone, "Etc/UTC");
var endDate = kendo.timezone.convert(scheduler.view().endDate(), timezone, "Etc/UTC");
//optionally add startTime / endTime of the view
var startTime = kendo.date.getMilliseconds(scheduler.view().startTime());
var endTime = kendo.date.getMilliseconds(scheduler.view().endTime());
endTime = endTime == 0 ? kendo.date.MS_PER_DAY : endTime;
var result = {
Start: new Date(startDate.getTime() - (startDate.getTimezoneOffset() * kendo.date.MS_PER_MINUTE) + startTime),
End: new Date(endDate.getTime() - (endDate.getTimezoneOffset() * kendo.date.MS_PER_MINUTE) + endTime)
}
return result;
}
</script>
<style>
.invalid-slot {
background: red !important;
cursor: no-drop;
}
</style>
</div>
But I don't know what I need to do in the controllers and models, if anything.
I just completed the implementation of KendoUI Scheduler by integrating it with SQL data base. However, I made use of JavaScript API to do so in my MVC project.
To load the data i.e. "read" and perform insert, update and delete just return the model in JSON format from controller. The Scheduler will bind the data for you, if it gets the "know" format.
return Json(**censored**.Models.LeaveRequest, JsonRequestBehavior.AllowGet);
Couple of important points:
1. KendoUI Scheduler depends a lot on unique id, so in case you have anything other than "id" - then "do" configure it in your scheduler.
In JS API it was done using following syntax, where EventID was the unique ID my SQL table.
schema: {
model: {
"id": "EventID",
"fields": {
"EventID": {
"type": "number"
},
....
Always return JSON data from your Insert, Update and Delete method from Controller. For instance:
public JsonResult UpdateCalendarEvent(string models)
{
...
return Json(censored.Models.LeaveRequest, JsonRequestBehavior.AllowGet);
}
In case of Insert, before returning the JSON object, do update the ID or EventID with latest row id, so Scheduler will sync up all data on client side and can perform update and delete operation appropriately.
Hope that helps!

How to use ExecuteStoreQuery for fetching data from Multiple tables

My application is in Asp.Net MVC3 coded in C#.Net. My issue is i want to get data from database using SQL query, for that i'm aware that i can use the below technique
Code to get data using ExecuteStoreQuery
var Complete_Data = db.ExecuteStoreQuery<Mytable>("select * from Mytable").ToList();
I have two issues
How to get the data in var Complete_Data when the data is coming from Multiple table (i.e the query has multiple joins).
I will be generating the selecting columns dynamically. The select query columns will generating dynamically.
Below is the sample example
string Field_Formation=string.Empty;
foreach (var item in My_Parameter_Collection_Logic_Variable)
{
Field_Formation+= item.Field_Name + ",";
}
Here My_Parameter_Collection_Logic_Variable is a variable declared in my code that will have a certain collection.
var Complete_Data = db.ExecuteStoreQuery<What_Class_To_Be_Taken_Here>("select" + Field_Formation + " from My_Tables_With_Multiple_Joins").ToList();
Need suggestion, whether it is possible to do such a stuff.
var Complete_Data = db.ExecuteStoreQuery<**What_Class_To_Be_Taken_Here**>
<What_Class_To_Be_Taken_Here> - this class must have properties like your Field_Formation.
For example if your select is:
"SELECT e.idExpense AS ExpenseID, e.idVehicle as VehicleID, d.Date AS Date1 .... join ... where ..."
create class like this:
public class ItemExample
{
private int VehicleID{ get; set; }
private int ExpenseID{ get; set; }
private DateTime? Date1 { get; set; }
}
You can write query using join and get your data from multiple tables.
for eg:-
var Complete_Data = db.ExecuteStoreQuery("select * from Table1 as T1 inner join Table2 as T2 on T1.id=T2.Id").ToList();
You will get all column of all table and then you can access using A.ColumnName or B.ColumnName.

Group By Sum Linq to SQL in C#

Really stuck with Linq to SQL grouping and summing, have searched everywhere but I don't understand enough to apply other solutions to my own.
I have a view in my database called view_ProjectTimeSummary, this has the following fields:
string_UserDescription
string_ProjectDescription
datetime_Date
double_Hours
I have a method which accepts a to and from date parameter and first creates this List<>:
List<view_UserTimeSummary> view_UserTimeSummaryToReturn =
(from linqtable_UserTimeSummaryView
in datacontext_UserTimeSummary.GetTable<view_UserTimeSummary>()
where linqtable_UserTimeSummaryView.datetime_Week <= datetime_To
&& linqtable_UserTimeSummaryView.datetime_Week >= datetime_From
select linqtable_UserTimeSummaryView).ToList<view_UserTimeSummary>();
Before returning the List (to be used as a datasource for a datagridview) I filter the string_UserDescription field using a parameter of the same name:
if (string_UserDescription != "")
{
view_UserTimeSummaryToReturn =
(from c in view_UserTimeSummaryToReturn
where c.string_UserDescription == string_UserDescription
select c).ToList<view_UserTimeSummary>();
}
return view_UserTimeSummaryToReturn;
How do I manipulate the resulting List<> to show the sum of the field double_Hours for that user and project between the to and from date parameters (and not separate entries for each date)?
e.g. a List<> with the following fields:
string_UserDescription
string_ProjectDescription
double_SumOfHoursBetweenToAndFromDate
Am I right that this would mean I would have to return a different type of List<> (since it has less fields than the view_UserTimeSummary)?
I have read that to get the sum it's something like 'group / by / into b' but don't understand how this syntax works from looking at other solutions... Can someone please help me?
Thanks
Steve
Start out by defining a class to hold the result:
public class GroupedRow
{
public string UserDescription {get;set;}
public string ProjectDescription {get;set;}
public double SumOfHoursBetweenToAndFromDate {get;set;}
}
Since you've already applied filtering, the only thing left to do is group.
List<GroupedRow> result =
(
from row in source
group row by new { row.UserDescription, row.ProjectDescription } into g
select new GroupedRow()
{
UserDescription = g.Key.UserDescription,
ProjectDescription = g.Key.ProjectDescription,
SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
}
).ToList();
(or the other syntax)
List<GroupedRow> result = source
.GroupBy(row => new {row.UserDescription, row.ProjectDescription })
.Select(g => new GroupedRow()
{
UserDescription = g.Key.UserDescription,
ProjectDescription = g.Key.ProjectDescription,
SumOfHoursBetweenToAndFromDate = g.Sum(x => x.Hours)
})
.ToList();