Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IOrderedEnumerable - asp.net-mvc

I am struggling with linq to get the datetime.
I am trying to get the info if the records are less than the current date
Here is the code:
public ActionResult _Events()
{
DateTime dt = DateTime.Now.Date;
var DocsFirst =(from t in db.tble_presentation
where dt >= EntityFunctions.TruncateTime(t.presentation_date)
select t).OrderByDescending(t => t.presentation_date).Take(2);
return PartialView(new Newsmodel
{
DocsList_list1 = DocsFirst,
});
}
but I get this following error
Cannot implicitly convert type 'System.Linq.IQueryable' to
'System.Linq.IOrderedEnumerable'. An explicit conversion exists
(are you missing a cast?)
thanks in advance
Hesh

It looks like DocsList_List1 is of type IOrderedEnumerable (as #Emre points out in the comment). To make the code compile, you either have to change the declaration of DocsList_list1 to be of a compatible type (probably IEnumerable) or make the result of the linq query an IOrderedEnumerable. An (somewhat ugly) way to do the latter:
var DocsFirst = (from t in db.tble_presentation
where dt >= EntityFunctions.TruncateTime(t.presentation_date)
select t).Take(2).AsEnumerable()
.OrderByDescending(t => t.presentation_date);
It's somewhat ugly because it does the ordering in memory instead of letting the database do it, but it still only reads the two requested elements thanks to Take(2) being placed before AsEnumerable().

Related

How to reference enum type in entity sql

I have the following (simplified) Entity SQL query:
SELECT VALUE a
FROM Customers AS a
WHERE a.Status NOT IN { 2, 3 }
The Status property is an enumeration type, call it CustomerStatus. The enumeration is defined in the EDMX file.
As it is, this query doesn't work, throwing an exception to the effect that CustomerStatus is incompatible with Int32 (its underlying type is int). However, I couldn't find a way to define a list of CustomerStatus values for the IN {} clause, no matter what namespace I prefixed to the enumeration name. For example,
SELECT VALUE a
FROM Customers AS a
WHERE a.Status NOT IN { MyModelEntities.CustomerStatus.Reject, MyModelEntities.CustomerStatus.Accept }
did not work, throwing an exception saying it could not find MyModelEntities.CustomerStatus in the container, or some such.
Eventually I resorted to casting the Status to int, such as
SELECT VALUE a
FROM Customers AS a
WHERE CAST(a.Status AS System.Int32) NOT IN { 2, 3 }
but I was hoping for a more elegant solution.
Oooh, you are writing Entity SQL directly. I see... Any reason you aren't using DbSet instead of writing Entity SQL by hand? Could always do
var statuses = new [] { Status.A, Status.B };
var query = context.SomeTable.Where(a => !statuses.Contains(a.Status)).ToList();

Breeze: Using Predicate with a Decimal DataType

I am trying to create a Predicate using a decimal data type but I get the following error:
Error retrieving data.A binary operator with incompatible types was detected.
Found operand types 'Edm.Decimal' and 'Edm.Double' for operator kind 'Equal'.
Error: A binary operator with incompatible types was detected. Found operand types
'Edm.Decimal' and 'Edm.Double' for operator kind 'Equal'.
Here is the code I am trying it with:
// engineSize equals 1.4 in this case.
predicate.create('engineLitreCapacity', '==', engineSize);
I'had the same issue. I found the mistery :)... I think that's somethings in naming convention related to metadata and the REST service controller sign: Eg:
Doesn't work
/*Breeze Controller Server Side*/
[HttpGet]
public IQueryable<Product> Items()
{
return _contextProvider.Context.Products;
}
/*Client*/
query = breeze.EntityQuery
.from("Items")
.where(Predicate.create('BasePrice', >', 1)
.orderBy(sortString)
.select(selectData)
.skip(skip)
.take(take)
.inlineCount();
It' works !!
/*Breeze Controller Server Side*/
[HttpGet]
public IQueryable<Product> Products()
{
return _contextProvider.Context.Products;
}
/*Client*/
query = breeze.EntityQuery
.from("Products")
.where(Predicate.create('BasePrice', >', 1)
.orderBy(sortString)
.select(selectData)
.skip(skip)
.take(take)
.inlineCount();
You need to parseFloat the engineSize:
predicate.create('engineLitreCapacity', '==', parseFloat(engineSize));
What is the datatype in metadata for the 'engineLitreCapacity' and does it match the datatype on your database for the same field? If not, how was your metadata initialized, via a FetchMetadata call or was it created by hand?

Getting only what is needed with Entity Framework

With a plain connection to SQL Server, you can specify what columns to return in a simple SELECT statement.
With EF:
Dim who = context.Doctors.Find(3) ' Primary key is an integer
The above returns all data that entity has... BUT... I would only like to do what you can with SQL and get only what I need.
Doing this:
Dim who= (From d In contect.Doctors
Where d.Regeneration = 3
Select New Doctor With {.Actor = d.Actor}).Single
Gives me this error:
The entity or complex type XXXXX cannot be constructed in a LINQ to Entities query.
So... How do I return only selected data from only one entity?
Basically, I'm not sure why, but Linq can't create the complex type. It would work if you were creating a anonymous type like (sorry c# code)
var who = (from x in contect.Doctors
where x.Regeneration == 3
select new { Actor = x.Actor }).Single();
you can then go
var doctor = new Doctor() {
Actor = who.Actor
};
but it can't build it as a strongly typed or complex type like you're trying to do with
var who = (from x in contect.Doctors
where x.Regeneration == 3
select new Doctor { Actor = x.Actor }).Single();
also you may want to be careful with the use of single, if there is no doctor with the regeneration number or there are more than one it will throw a exception, singleordefault is safer but it will throw a exception if there is more than one match. First or Firstordefault are much better options First will throw a exception only if none exist and Firstordefault can handle pretty much anything
The best way to do this is by setting the wanted properties in ViewModel "or DTO if you're dealing with upper levels"
Then as your example the ViewModel will be:
public class DoctorViewModel{
public string Actor {get;set;}
// You can add as many properties as you want
}
then the query will be:
var who = (From d In contect.Doctors
Where d.Regeneration = 3
Select New DoctorViewModel {Actor = d.Actor}).Single();
Sorry i wrote the code with C# but i think the idea is clear :)
You can just simply do this:
Dim who= (From d In contect.Doctors
Where d.Regeneration = 3
Select d.Actor).Single
Try this
Dim who = contect.Doctors.SingleOrDefault(Function(d) d.Regeneration = 3).Actor

Spark null operator not working with nullable types

I have a nullable DateTime I want to show in ShortDate format if it has a value, but I can't get it right. I am trying to use the null operator ($!{}) here.
It should work like this:
<td>$!{period.Enddate.Value.ToShortDateString()}</td>
But this gives an InvalidOperationException: nullable object must have a value.
Removing the 'Value' part won't work either, that will give the obvious 'System.Nullable has no definition for ToShortDateString' message.
With the conditional operator it works fine, but that one only works for attributes like this:
<td value="$!{period.Enddate.Value.ToShortDateString()}?{period.Enddate.HasValue}"></td>
And I am trying to get it inside the td element, not as an attribute for td.
Am I doing something wrong here, or is this a known issue?
I understand that catching an InvalidOperationException (thrown by the Nullable class) is trickier than catching a NullReferenceException, but I think it is a serious flaw.
Cheers,
Ronald
As of Spark v1.6, here are some options:
use a format specfier -
<td>${ string.Format("{0:M/dd/yy}", period.Enddate) }</td>
or create an additional presentation property -
public string EnddateText
{
get
{
var result = Enddate.HasValue ? Enddate.Value.ToShortDateString() : string.Empty;
return result;
}
}
<td>${ period.EnddateText }</td>

Executing Method Against DataContext Returning Inserted ID

Is there any way to use DataContext to execute some explicit SQL and return the auto-increment primary key value of the inserted row without using ExecuteMethodCall? All I want to do is insert some data into a table and get back the newly created primary key but without using LINQ (I use explicit SQL in my queries, just using LINQ to model the data).
Cheers
EDIT: Basically, I want to do this:
public int CreateSomething(Something somethingToCreate)
{
string query = "MyFunkyQuery";
this.ExecuteCommand(query);
// return back the ID of the inserted value here!
}
SOLUTION
This one took a while. You have to pass a reference for the OUTPUT parameter in your sproc in your parameter list of the calling function like so:
[Parameter(Name = "InsertedContractID", DbType = "Int")] ref System.Nullable<int> insertedContractID
Then you have to do
insertedContractID = ((System.Nullable<int>)(result.GetParameterValue(16)));
once you've called it. Then you can use this outside of it:
public int? CreateContract(Contract contractToCreate)
{
System.Nullable<int> insertedContractID = null; ref insertedContractID);
return insertedContractID;
}
Take heavy note of GetParameterValue(16). It's indexed to whichever parameter it is in your parameter list (this isn't the full code, by the way).
You can use something like this:
int newID = myDataContext.ExecuteQuery<int>(
"INSERT INTO MyTable (Col1, Col2) VALUES ({0}, {1});
SELECT Convert(Int, ##IDENTITY)",
val1, val2).First();
The key is in converting ##IDENTITY in type int, like Ben sugested.
If you insist on using raw sql queries, then why not just use sprocs for your inserts? You could get the identity returned through an output parameters.
I'm not the greatest at SQL, but I broke out LinqPad and came up with this. It's a big hack in my opinion, but it works ... kinda.
DataContext.ExecuteQuery<T>() returns an IEnumerable<T> where T is a mapped linq entity. The extra select I added will only populate the YourPrimaryKey property.
public int CreateSomething(Something somethingToCreate)
{
// sub out your versions of YourLinqEntity & YourPrimaryKey
string query = "MyFunkyQuery" + "select Convert(Int, SCOPE_IDENTITY()) as [YourPrimaryKey]";
var result = this.ExecuteQuery<YourLinqEntity>(query);
return result.First().YourPrimaryKey;
}
You'll need to modify your insert statement to include a SELECT ##Identity (SQL Server) or similar at the end.

Resources