How to handle ObjectResult in Entity Framework 4 - c#

In Entity Framework 4, I'm facing a problem when I use function import to a stored procedure and then using as a scalar value. It generates the code below:
public virtual ObjectResult<Nullable<int>> GetTopEmployee()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<int>("GetTopEmployee");
}
How do I use the return value of this method?
For example, this code works fine:
NorthwindEntities db = new NorthwindEntities();
var i = db.GetTopEmployee();
But I want to use return values only as int. If I use return value as non while in function import it give -1 as output.
When I try the code below:
NorthwindEntities db2 = new NorthwindEntities();
int j = db.GetTopEmployee();
It throws an error saying:
Cannot implicitly convert type 'System.Data.Objects.ObjectResult' to 'int'
How do I parse the above?

Notice that the return type of GetTopEmployee is an ObjectResult<Nullable<int>>. ObjectResult<T> implements IEnumerable<T> so your method is capable of returning more than one Nullable<int>.
I assume you are trying to get some form of Id for the employee. If you are absolutely sure you are only going to get one result you could use the following code to get that Id.
var topId = db.GetTopEmployee().FirstOrDefault();
topId could be null. You will have to use topId.Value or var result = topId ?? -1; to get an int result.
NorthwindEntities db = new NorthwindEntities();
int j = db.GetTopEmployee().FirstOrDefault() ?? -1;

Related

How to assign ObjectResult<> from EF

After using DB first approach with EF my context.cs file has the follwing for a stored procedure:
public virtual ObjectResult<selectCases_Result> selectCases()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<selectCases_Result>("selectPurgeCaseFolio");
}
In a sepearte class file I'm trying to invoke it to get the result with the following:
public SelectCases()
{
var result = _context.selectCases;
}
However the error I get is on result:
"Cannot assign method group to an implicitly-typed local variable"
How can I get the result of this select query into a dataset or anyother type of object to see the results?
You forgot to call the method (with ())
var result = _context.selectCases();
You are trying to call it like a property when you should be calling it as a method

linq to entity query getting error

I am trying to amend a c# project. I am a vb.vet programmer so having a few issues as I am new to linq. I am trying to run a Linq to Entity query. I want to select the MapEast where town = town. I keep get an error The specified cast from a materialized System.Decimal' type to the 'System.Int32' type is not valid.. I would like to put a max(1) in here too so it returns only the highest number.
var topEast = 0;
try
{
topEast = this._uow.Addresses
.Where(a =>
a.Town.Trim().ToUpper() == town.Trim().ToUpper())
.Select(m => m.MapEast).FirstOrDefault ();
return -1;
}
catch
{
return -1;
}
Thanks
var is used for implicitly typed local variable. When you defined var topEast = 0;, topEast was implicitly assigned type int, and not decimal as per your query. You can fix it by explicitly defining topEast as decimal.
decimal topEast = 0;
I would like to put a max(1) in here too so it returns only the
highest number.
Not really sure what you are trying to return, because you are returning -1 from try as well as catch block. If you are trying to return the Max value of MapEast field then you will need Enumerable.Max, otherwise FirstOrDefault would return the first item or null based on criteria.

c# Asp.net Error :Specified cast is not valid

Here is a portion of a code ..
public Admin_GetCourseById_spResult GetCourseById(long? courseId, short languageId)
{
ISQUserDataContext db = CreateDataContext();
Admin_GetCourseById_spResult result;
result = db.Admin_GetCourseById_sp(courseId,false,languageId).FirstOrDefault();
return result;
}
the third line in the function throws error Specified cast is not valid.
Any clue about whats happening ??
Small rewrite (needs more work)
public Course GetCourseById(long? courseId, short languageId)
{
ISQUserDataContext db = CreateDataContext();
return new Course(db.Admin_GetCourseById_sp(courseId, false, languageId).FirstOrDefault());
}
and then add a class Course with a constructor accepting the returntype of Admin_GetCourseById_sp to build a nice Course object.
Your
db.Admin_GetCourseById_sp(courseId,false,languageId).FirstOrDefault() line returns a datarow.
(It might return null if there are no data)
Therefore what you can do is this,
you can set each attribute of your
Admin_GetCourseById_spResult result object with the matching value from the returned datarow
i.e result.courseId = row["course_id"].ToString()
{ I assumed that courseId is String in your Admin_GetCourseById_spResult class + the matching db column is course_id.
You have given little data, so could answer only like this. Good Luck !

How to Assign a Query Result to an Integer Array

public List<Workflow> GetMyWorkflows(int[] MyRoles)
{
int[] myWorkflowIDs = new int[] { };
RapidWorkflowDataContext context = new RapidWorkflowDataContext();
var query = from w in context.WorkflowRoles
where MyRoles.Contains((int)w.RoleID)
select w.WorkflowID;
var distinctWorkflows = query.Distinct();
myWorkflowIDs = distinctWorkflows.toArray();
return myWorkflowIDs;
}
In this method I want to retrieve an array of workflows that a user can
access.
I get the following error : Cannot implicitly convert type 'int?[]' to 'int[]'
I want to retrieve an array of workflows
But your method must return a List<Workflow> or a List<int>.
So you should skip the array idea. The other issue is between int and int?. You can solve that in the select clause with select w.WorkflowID.Value or select w.WorkflowID ?? 0. Or simply select w for a List<Workflow>.
Also it is a good idea to dispose a context when it becomes unreachable.
public List<int> GetMyWorkflows(int[] MyRoles)
{
using (RapidWorkflowDataContext context = new RapidWorkflowDataContext())
{
var query = from w in context.WorkflowRoles
where MyRoles.Contains((int)w.RoleID)
select w.WorkflowID ?? 0;
// select w; to return a List<WorkFlow>
var distinctWorkflows = query.Distinct();
return distinctWorkflows.ToList(); // ToList because we are closing the Context
}
}
I'm going to guess that WorkflowID is of type int?. If you are certain that it cannot be null, change your central query to:
var query = from w in context.WorkflowRoles
where MyRoles.Contains((int)w.RoleID)
select w.WorkflowID.Value;
This will ensure that query is now of type IEnumerable<int> instead of IEnumerable<int?>, with the int following on throuhh the Distinct() and ToArray() functions.
This seems like a pretty good error to me
Cannot convert type 'int?[]' to 'int[]'
You must have an array of type int? and be trying to implicitly convert it to int.
Therefore you have two options - stop trying to implicitly convert, and allow the result to be int?[], like this:
int?[] myWorkflowIDs = new int?[] { };
or force the convert to take place, like this:
RapidWorkflowDataContext context = new RapidWorkflowDataContext();
var query = from w in context.WorkflowRoles
where MyRoles.Contains((int)w.RoleID)
select (int)w.WorkflowID;
// or w.WorkflowID ?? 0; as necessary
So int? can also be written Nullable<int> which is basically an int that can take null values. For example:
int? nullableNumber = 5; // Set to a value
nullableNumber = null? // Set to null (which is possible because int? is nullable).
As you can imagine, Nullable<int> is useful for databases because sometimes you might have a column that has null values, and so this type gives a useful means of mapping to this sort of value. The problem, though is that in your code you have to deal with two different types, int vs. int?. You can cast between the two values by using:
// If the nullable-integer is not-null then use it's value, else default to `0`.
int nonNullable = nullableNumber ?? 0;
which will replace nulls with 0 if the value is null. Or you can just store your myWorkflowIDs in a nullable value (Nullable<int>[] or int?[]), which semantically better reflects what the column value in the database actually is.

Linq syntax error in ASP MVC controller method

I have a Linq query I need to use in my Index method in the page's controller, however I am getting the following error on the "select new" portion of the code:
Error
Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'string'
Action method
public ActionResult Index(string query)
{
var agentProductTraining = "";
if (String.IsNullOrEmpty(query))
{
BlankIndex();
}
else
{
agentProductTraining = from course in db.Course
where
course.CourseDescription.Contains(query)
select new
{
course.CourseCode,
course.CourseDescription,
course.Partner,
course.Status,
course.LastChangeDate,
course.LastChangeOperator
};
}
return View(agentProductTraining.ToList());
}
As the error clearly states, you cannot assign the result of a LINQ query (IQueryable<T>) to a variable of type string.
You should declare the variable in that line:
var agentProductTraining = select ...
You've initialized the variable as a string, so the compiler makes the variable a string type (since you've user the var keyword), but then tried to assign a collection of anonymous types to it.
You can declare it as an object instead or var:
object agentProductTraining; // can safely be overwritten
Also I assume you mean:
return BlankIndex();
in the if block. Otherwise it will fall through to
return View(agentProductTraining.ToList());
where agentProductTraining is going to be null
Of course if you use return BlankIndex in the if block you can simplify the whole thing:
if (String.IsNullOrEmpty(query))
{
return BlankIndex();
}
// don't need an `else` here since the if will return to the caller
var agentProductTraining = from course in db.Course
where
course.CourseDescription.Contains(query)
select new
{
course.CourseCode,
course.CourseDescription,
course.Partner,
course.Status,
course.LastChangeDate,
course.LastChangeOperator
};
return View(agentProductTraining.ToList());

Categories