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
Related
I am using Dapper with the Dapper.SimpleCrud extension.
In my Dapper class, I have made an abstraction of the insert method, like this:
public static int Insert(object entity) {
try {
using (SqlConnection sqlConnection = new SqlConnection(connectionString)) {
sqlConnection.Open();
return sqlConnection.Insert(entity) ?? -1;
}
}
catch(Exception ex) {
// log
return -1;
}
}
This lets me call insert and pass an object of any type that is in the db.
The code that currently calls this method looks like this:
DapperORM.Insert(new Menu {
RestaurantID = RestaurantID,
Name = Name});
This throws an error: {"Incorrect syntax near ')'."}
Ok, so now I think there is something wierd with the data I pass in or something. But no. When I change my own Insert method to take a Menu-object instead of a general object, it works.
The Dapper.SimpleCrud Insert overload method obviously can't figure out which object it is. Do you know how to fix it?
Have you had a look at the generated SQL? In stack trace may be? I guess it must be missing name of database table. Yes; I guess. Because I never used SimpleCRUD.
an object of any type that is in the db
How do SimpleCRUD know that the object you send in is "of type that is in the db"?
I think object type parameter is the problem. To accept "an object of any type that is in the db" you should consider converting your method to use generic type instead of object.
When I change my own Insert method to take a Menu-object instead of a general object, it works.
This confirms my earlier diagnosis.
Convert your method to something like below:
public static int Insert<TPoco>(TPoco entity) where TPoco : class
or
public static int Insert<TPoco>(TPoco entity) where TPoco : BasePoco
or similar as per your other code structure.
I need to complete my task using only stored procedures.
In my app I have Models called 'Document' and 'DocumentInfo' which refers to mysql tables. For example I got simplest stored procedure to get list of documentInfos by Filename:
SQL:
CREATE PROCEDURE `GetDocumentByName` (DocName varchar(255))
BEGIN
Select * from GetAllDocuments where DocumentName like DocName;
END$$
C#:
public List<DocumentsInfo> GetDocumentByName(string Filename)
{
return db.DocumentsInfo.FromSql("CALL GetDocumentByName({0})", Filename).ToList();
}
As you can see I use db - this is dbContext. DocumentsInfo it's my model and I returned a list of DocumentsInfo objects. But what if I don't need to return whole object, but only one column?
Now I need to do the same but with 'Document' but only this time I need to take only one field - DocumentBody, which is BLOB
SQL:
CREATE PROCEDURE `GetDocumentBodyById` (DocumentBodyID INT(11))
BEGIN
Select DocumentBody from Document where idDocumentBody = DocumentBodyID;
END$$
C#:
var test = db.FromSql("CALL GetDocumentBodyById({0})", DocumentID).FirstOrDefault();
Gives me an error:
'DBContext' does not contain a definition for 'FromSql' and no
accessible extension method 'FromSql' accepting a first argument of
type 'DBContext' could be found (are you missing a using directive or
an assembly reference?)
Also tried to use this option:
var test = db.Database.SqlQuery<object>("CALL GetDocumentBodyById({0})", DocumentID).FirstOrDefault();
But received new error:
'DatabaseFacade' does not contain a definition for 'SqlQuery' and no
accessible extension method 'SqlQuery'
How to call stored procedure which should return only one value, not whole model object? Is it possible with .net core?
For FromSql, it is used with Query, you could define a new model for return result.
public class ResultDto
{
public string Name { get; set; }
}
Define Query in OnModelCreating
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Query<ResultDto>();
}
Useage:
var result = _context.Query<ResultDto>().FromSql("exec GetDocumentBodyById {0}", 1).ToList();
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 !
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());
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;