How to execute a LINQ to Entities query, pulling values from an existing resultset variable instead of against the DB - stored-procedures

To provide some context, I'm using jqGrid to conduct a server side search on a datetime field, truncating the time portion server side, and then fetching results via a stored procedure. This is being done using System.Dynamic.Linq, which I've modified slightly as per this question here. I'm using EF6 Code First approach. The relevant portion of the code looks something like this:
//For matching date instead of datetime values
if (wc.Clause.Contains("Date"))
{
wc.Clause = wc.Clause.Replace("DeliveryDate", "DbFunctions.TruncateTime(DeliveryDate)");
}
results = dataFileDB.Database.SqlQuery<Document>("exec [dbo].[sp_getDocumentDetails]").AsQueryable().Where(wc.Clause, wc.FormatObjects);
The problem I'm having is that because the query is fetched using a stored procedure, I get an exception on the last line saying
System.NotSupportedException: This function can only be invoked from LINQ to Entities.
at System.Data.Entity.DbFunctions.TruncateTime(Nullable`1 dateValue)
In other places where I've used a lambda query to fetch directly from the entity itself and apply the where clause filter, the filtering is done correctly.
What I was trying to do (and I'm not sure if this is possible but...) was run an entity query against the results variable and apply the where clause to that variable but I've had no luck. Is this the right way to go or is there another approach I could take?
Thanks in advance!

Got it... I was overcomplicating things too much.
I just converted the DateTime field to a Date field when returning it via the stored procedure. Doing so no longer required me to use the DbFunctions.TruncateTime method, thereby resolving my issue.
Hope this helps someone else!

Related

DbContext Changes Date which is Stored in Database Upon Object Graph Creation

This question is now a curiosity, more than anything. Dates will be the end of me.
Using EF 6.
I am storing a date and in the same http request, pulling the object back out of the database.
When I look at the SQL which EF sends, the milliseconds of the date in question which are returned are the same as that which are stored in the db (expected behaviour).
BUT, when EF deserializes that into the object graph in memory, the milliseconds are different.
So, I save '2018-10-16 21:46:22.293'
SQL retrieves '2018-10-16 21:46:22.293'
EF deserializes to 2018-10-16 21:46:22.294 !
I created a workaround by hitting the db with a raw ADO.NET query that gets the exact date ('2018-10-16 21:46:22.293').
Even weirder, if I use a fresh DbContext and grab the whole object with that, the date is fine i.e. '2018-10-16 21:46:22.293'
So, it is only when I use the same DbContext that save the data, to retrieve the data that the date gets rounded (or something).
Anyone seen this weird behaviour? Is there a better fix than either raw SQL (ado.net) or a fresh DbContext?
Cheers
You can bypass the EF cache by appending .AsNoTracking() to your retrieval query.

Mvc: The use of IQueryable and Asqueryable is not clear

I found some lines of code online and I understand the first two lines. Data of a particular
type is cached and stored in the two properties of the models below.
model.payment = (List<CompInfor>)HttpRuntime.Cache[cacheKey + "_received"];
model.FilteredPayment = (List<CompInfor>)HttpRuntime.Cache[cacheKey + "_received"];
However I don't understand the line below as I have never written code like this below.
Please what does this line do? What does it mean? I know you can save a lot of resources by using IQueryable.
IQueryable<CompInfor> payment = model.FilteredPayment.AsQueryable<CompInfor>();
It simply returns an instance of the IQueryable<T> interface which will utilize a query provider to act upon the object in question (in your case, the model.FilteredPayment list). It doesn't seem to make much sense when you're acting against a List locally, but (as an example) in the case of entity framework where you build query statement to be executed against a database via SQL, the Linq to Entities query provider processes the IQueryable into the appropriate SQL statement for execution against the database and processes the results.

How does Breeze handle database column defaults?

I can't find any info about this in the documentation, so I will ask here. How does breeze handle database column defaults? I have required columns in my database, but there are also default static values supplied for these in the database column definitions. Normally, I can insert null into these columns, and the new records will get the default. However, breeze doesn't seem to be aware of database column defaults, and the entities that have null in these columns fail validation on saving.
Thanks,
Mathias
Try editing the edmx xml by adding StoreGeneratedPattern = "Computed" attribute to the column with default value in the DB.
Edit:
Actually, before doing editing the xml, try setting the StoreGeneratedPattern property to Computed in the model editor itself.
Update:
This was fixed in Breeze 1.4.6 ( or later), available now.
Original Post:
There is currently in a bug in Breeze that should be fixed in the next release, out in about week. When this fix gets in then breeze will honor any defaultValues it finds in the EntityFramework data model.
One problem though is while it is easy to get 'defaultValues' into a Model First Entity Framework model via the properties editor, it's actually difficult to get it into a Code First EF model, unless you use fluent configuration. Unfortunately, EF ignores the [DefaultValue] attribute when constructing Code First model metadata.
One workaround that you can use now is to poke the 'defaultValue' directly onto any dataProperty. Something like:
var customerType = myEntityManager.metadataStore.getEntityType("Customer");
var fooProperty = customerType.getProperty("foo");
fooProperty.defaultValue = 123;

How to make UPDATE queries in LINQ to SQL?

I like using LINQ to SQL. The only problem is that I don't like the default way of updating tables.
Let's say I have the following table with the following columns:
ID (primary key), value1, value2, value3, value4, value5
When I need to update something I call
UPDATE ... WHERE ID=#id
LINQ to SQL calls
UPDATE ... WHERE ID=#id and value1=#value1 and value2=#value2 and value3=#value3 and value4=#value4 and value5=#value5
I can override this behavior by adding
UpdateCheck=UpdateCheck.Never
to every column, but with every update of the DataContext class with the GUI, this will be erased. Is there any way to tell LINQ to use this way of updating data?
I'm confused by this statement:
but with every update of the DataContext class with the GUI, this will be erased. Is there any way to tell LINQ to use this way of updating data?
By "the GUI", do you mean the Linq to SQL designer? Because the property sheet for each member has an "Update Check" property that you can set to "Never". If you are manually editing the .designer.cs file, don't do that, instead change the Update Check setting in the actual designer.
Designer Screen http://img29.imageshack.us/img29/7912/updatecheckdesigner.png
Please note: The "default way" of updating used by Linq to SQL is called optimistic concurrency, and is a way of preventing conflicting updates from multiple users. If you turn this off by using the method above, you have to be prepared to deal with the fact that if two users have the same record open at the same time, the second user's changes will overwrite the first user's changes without any warning or confirmation. Be sure that this is the behaviour you really want.
Unfortunately, no, there's not. You have to edit the DBML manually after it is generated (or updated) - which is a pain (or use the Designer as already mentioned in the other answer).
When I last used L2S on a project, I wrote a quick utility which ran post-generation and fixed it up, but it's an unnecessary pain which (c)shouldn't be required IMHO.
Ran into this one myself. The trick is to change the way one generates the DBML--such as using l2st4. Then you can set that pesky UpdateCheck property to always be never by modifying the template.
That is how Linq works. Why don't you like this update behavior?
Read about optimistic concurrency
http://msdn.microsoft.com/en-us/library/bb399373.aspx

Linq to Enities: Result set not getting updated after Stored Procedure Call

In LINQ to Entities, I map the result set of a stored procedure to an entity.
Within the stored procedure, I execute some update statements and return the result set by running a SELECT query and mapping that result set to the entity.
The database rows get updated correctly, but the entities returned are not reflecting the changes. Instead, the data before the update is getting returned?
Any suggestions?
Thank you.
Abe
Actually, it turns out the DataContext.Refresh method solved my problem at
http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.refresh.aspx
Here's my code:
db.Refresh(System.Data.Objects.RefreshMode.StoreWins, affectedProjectTasks);
Thanks Marc for pointing me to the right direction!
Abe
Are the entities in question already cached in the context? (i.e. have you queried them already?)
If so, the identity manager will always give you back the original object (rather than creating a new object with the same identity in the same context). Hence for data that has already been read (by other queries) only the identity/primary-key field(s) are considered.

Resources