Get Getdate in Entity Frame work 2013 - entity-framework-4

I'm new to Entity Framework.
How can I get server date (get date) in Entity Framework? (I'm using Visual Studio 2013).
I tried for SqlFunction.GetDate(). Other than this, is there any other method to get the date?

Try to be more precise in your questions. It would be useful for us to know, what you want to achieve to propose you the simplest way.
To get date directly from server, you should use ExecuteQuery() method and call SQL method. In your context add method like this:
public DateTime GetDate()
{
return ExecuteQuery<DateTime>("SELECT GETDATE()").First();
}
where
SELECT GETDATE()
is raw T-SQL method.
To just have a date of addition entity the simplest way is to call method on the level of your app. For this purpose add property to one of your entity:
public DateTime DateAdded { get; set; }
When you'll be adding new entity invoke (db means context object):
db.DateAdded = DateTime.Now;
You will get current date thanks to these operations. Good Luck!

Try DbFunctions.CreateDateTime

Related

Web Api OData Query for custom type

I've defined my own struct that represents DateTime with TimeZoneInfo so I can work with UTC time while keeping the information about timezone.
I would like to get these objects with OData query, but it fails when I try to use $orderby on this properties of this type. I was able to get results when I queried $orderBy=Timestamp/Value/UniversalTime but I would like to use just $orderBy=Timestamp
Is there any possibility to order collection with this type?
public struct DateTimeWithZone : IComparable<DateTime>, IComparable<DateTimeWithZone>, IFormattable
{
private readonly DateTime _utcDateTime;
private readonly TimeZoneInfo _timeZone;
public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
{
if (timeZone == null)
{
throw new NoNullAllowedException(nameof(timeZone));
}
_utcDateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
_timeZone = timeZone;
}
...
}
With model defined like this:
public class ClientViewModel
{
public string Name { get; set; }
public DateTimeWithZone? Timestamp { get; set; }
}
And this is how it is used:
public IHttpActionResult GetAll(ODataQueryOptions<ClientViewModel> options)
{
var fromService = _clientsClient.GetAllClients().MapTo<ClientViewModel>(MappingStrategy).AsQueryable();
var totalCount = fromService.Count();
var results = options.ApplyTo(fromService); // <-- Fails here
return Ok(new PageResult<ClientViewModel>(
results as IEnumerable<ClientViewModel>,
Request.ODataProperties().NextLink,
totalCount));
}
Fails with The $orderby expression must evaluate to a single value of primitive type.
we had some similar issue with complex type ordering. Maybe this can be of assistance in your scenario as well. In our case (which is not 100% identical) we use a two phase approach:
Rewriting ODataQueryOptions
separating the extneral model (ODATA) and the internal model (EntityFramework in our case)
Rewriting ODataQueryOptions
You mention that the format $orderBy=Timestamp/Value/UniversalTime is accepted and is processed properly by ODATA. So you can rewrite the value basically by extracting the $orderby value and reinserting it with in your working format.
I described two ways on how to do this in my post Modifying ODataQueryOptions on the fly (full code included), which take existing options recreate new options by constructing a new Uri. In your case you would extract Timestamp from $orderBy=Timestamp and reinsert as with $orderBy=Timestamp/Value/UniversalTime.
Separating External and Internal Model
In addition, we used two models for the public facing API and the internal / persistence layer. On the internal side we used different properties which we grouped into a navigation property (which only exists on the public side). With this approach the user is able to specify an option via an $expand=VirtualNavigationProperty/TimeZoneInfo and $orderby=.... Internally you do not have to use the complex data type, but keep using DateTimeOffset which already holds that information. I described this separation and mapping of virtual navigation properties in the following post:
Separating your ODATA Models from the Persistence Layer with AutoMapper
More Fun with your ODATA Models and AutoMapper
According to your question it should be sufficient to rewrite the query options in the controller as you did mention that the (little bit longer) $orderby format is already working as expected and you only wanted a more convenient query syntax.
Regards, Ronald

DateTime.Date does not work in HTML5

I want do have my DateTime get displayed without the time.
So I use
item.AD_Date.Date
to cut off the time.
In the Model ( I use MVC) AD_Date is set up like this:
public System.DateTime AD_Date { get; set; }
But I get my date like this:
01.03.2013 00:00:00
What did I do wrong?
The Date property just returns a DateTime with the same date, but at midnight. There's no difference between "a DateTime at midnight" and "a DateTime just representing a date" (unfortunately).
You need to change how your DateTime is formatted to only show the date - either by annotating the model or by changing the view.
(Alternatively, use my Noda Time library which has different types for the different kinds of data you want to represent. I haven't tried using it with MVC, but at least for the formatting side it should work okay...)
If someone is facing the same problem, here is my formatting :
#String.Format("{0:yyyy-MM-dd}", item.AD_Date)

How to build Dynamic Linq from Request.QueryString?

I'm currently working on feature to implement/build a filter through Request.QueryString. The idea here is the filter can be on any property with in the Model For ex.,
public class Alert{
public string Name;
public string Status;
public Datetime StartDate;
public Datetime EndDate;
public bool IsActive;
}
so the calling client wants to pass something like this in the query string startdate >=2013-10-1&Name=John&IsActive=false. I'm using System.Linq.Dynamic from Scottgu to build the where clause which takes a string but the format to build is kind of killing me. I need some pointers on the format and I'm doing the type checking through reflection before executing this and also I'm filtering this against the data that came back from DB and not passing this into the db.Any help is really appreciated!
Don't reinvent the wheel if you don't need to :P
Have a look at Odata, and the .net web.api
That should do what you need.

MVC control databinding with nosql database

I have a MVC application that I am building with RavenDB as the main database
In my application, I need a calendar control that needs to be strongly data binded (with RavenDB data)I need calendar control to post data to raven, show dates from ravendb on a calendar control (two way data flow) etc..
Any one have any suggestions for me.. probably some one who did this sort of thing using ravendb, mvc and a calendar control.
What calendar control out there best suits my needs here.. a Jquery date picker? Telerik MVC Calendar ? or any other?
Any input, comments, help is appreciated.
Well RavenDB allows you to deserialize into a regular POCO class, so given a class like this:
public class User
{
public string Id { get; set; }
public DateTime date { get; set; }
}
You can then just load a doc like so:
session.Load<User>("users/1");
From that point onwards you can use the object however you want. You can bind against it, pass it into the view, add attributes to it, etc.

Creating an ActionLink with a DateTime in the query string in ASP.NET MVC

I have a search form with a DateTime search criterion, plus some other criteria:
<form method="get" action="/app/search">
<input type="text" value="13/01/2010" name="BeginDate"/>
<input type="text" value="blah" name="SomeOtherCriterion"/>
<form>
So I have a Search controller with a default Action (let's call it Index) and with a SearchCriteria parameter.
public class SearchController
{
public ActionResult Index(SearchCriteria searchCriteria) {//blah }
}
public class SearchCriteria
{
public DateTime BeginDate {get; set;}
public string SomeOtherCriterion {get; set;}
}
Now if I want to create an ActionLink, passing in a SearchCriteria value, thus:
Html.ActionLink("Search", "Index", searchCriteria)
I get the BeginDate query string parameter in US format. Looking on Google and poking around in System.Web.Routing using Reflector it seems to be because it uses the InvariantCulture, so there's nothing I can do about it.
It seems like noone has asked this question before so I guess I'm doing something very stupid.... Please help!
EDIT: Pass in SearchCriteria to ActionLink rather than anonymous object to show why I can't just do the custom ToString() myself.
Given that the framework appears to be hard-coded to handle this piece of data using InvariantCulture, I don't think there's much you can do to make it work transparently.
There is one ugly option - download the MVC source and rip out the code for all the offending classes from Route down to ParsedRoute to create your own RouteBase implementation that does what you need.
If I absolutely had to keep the DateTime declaration on the SearchCriteria class, then that's the route (sorry for the pun) I would choose.
However, a far easier solution would be to change your SearchCriteria class to use a slightly different declaration for the DateTime field, based on a type like this:
public class MyDateTime
{
public DateTime Value { get; set; }
//for passing MyDateTime in place of a DateTime without casting
public static implicit operator DateTime(MyDateTime instance) { return instance.Value; }
//so you can assign a MyDateTime from a DateTime without a cast
//- e.g. MyDateTime dt = DateTime.Now
public static implicit operator MyDateTime(DateTime instance) { return new MyDateTime() { Value = instance }; }
//override ToString so that CultureInfo.CurrentCulture is used correctly.
public override string ToString()
{
return Value.ToString(CultureInfo.CurrentUICulture);
}
}
In theory you should be able to roll out this change without too much fuss.
The big work could be if you have a lot of code that uses members (e.g. .Days etc) of the DateTime instance in SearchCriteria: you either have to reproduce those members on MyDateTime, wrapping around the inner DateTime Value or change all the code to use .Value.Member.
To avoid issues related to Regional Settings and "Culture",
I treat date and time as separate unbound fields and then
assemble them into DateTime in my Controller.
Example:
Year [ ] Month [ ] Day [ ]
I always present separate textboxes for year, month, and day, in that order so that there can be no confusion between U.S. format (month/day/year) and more or less the rest of the world's format (day/month/year).
Can you provide a formatted date in your ActionLink? Try this:
Html.ActionLink("Search",
"Index",
new {BeginDate =
DateTime.Now.ToString("d", new CultureInfo("pt-BR");})
Of course this changes BeginDate to a string instead of a DateTime... but maybe that will work for you?
We use ISO ("s" in a format string -- YYYY-MM-DDTHH:MM:SS) format for this. It works correctly, and JavaScript can handle it as well.
Perhaps you could use a Model Binder to format and parse the date? Just re-read the article and noticed that it does not format the date...Probably not going to work out. I'll leave the answer though in case it provides any unintentional inspiration :)
poking around in System.Web.Routing using Reflector it
seems to be because it uses the
InvariantCulture
Are you realy shure about this? The parts of Modelbinding and UrlBuilding I checked used CurrentCulture. Can you check what happens if you set the CurrentCulture before rendering the link?
Get the ASP.NET MVC 1.0 book written by Scott Hanselman, Scott Guthrie, Phil Haack, and Rob Conery. They actually do this exact scenario in the book. They use a specific route. I am looking at it right now on page 216.
They do it by breaking up day, month, and year. Then it is your responsibility to use those values as they come back.

Resources