dapper rainbow MissingMethodException - c#

Why do I get this exception? The code isn't the same but close to the 'demo' https://gist.github.com/1599013
Exception: MissingMethodException
Desc:
Method not found: 'System.Collections.Generic.IEnumerable1<System.Object> Dapper.SqlMapper.Query(System.Data.IDbConnection, System.String, System.Object, System.Data.IDbTransaction, Boolean, System.Nullable1, System.Nullable`1)'.
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using Dapper;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace daconsole2
{
class Program
{
class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime? LastPurchase { get; set; }
}
// container with all the tables
class MyDatabase : Database<MyDatabase>
{
public Table<Product> Products { get; set; }
}
//*/
static void Main(string[] args)
{
var cnn = new MySqlConnection("uid=name;pwd=pw;Port=3306;database=test");
cnn.Open();
var db = MyDatabase.Init(cnn, commandTimeout: 2);
//if(false)
db.Execute(#"create table Products (
Id int primary key,
Name varchar(20),
Description TEXT,
LastPurchase datetime)");
var productId = db.Products.Insert(new { Name = "Hello", Description = "Nothing" });
//var db = cnn;
Console.ReadKey();
}
}
}

We had this same problem, and it turned out to be that some of the projects in the solution were referencing different versions of Dapper.
For example, one project used a runtime version that showed v4.0.30319 in the Properties window.
Another project had a Dapper runtime version of v2.0.50727 (.NET 3.5).
As soon as I set them all to the v2.0.50727 version, this error went away.
*It should be noted that they both show File Version 1.12.0.0, so this is not a reliable way to tell them apart.

Related

Guid[]:How to query and fetch details from Cosmos DB?

I am working with Azure CosmosDB. I am having below GetProgramsByStudentIDAsync method which needs to fetch all the programs associated to the studentID (Note that studentID is of type Guid).
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Threading.Tasks;
public async Task<ProgramContainer> GetProgramsByStudentIDAsync(Guid[] studentIds)
{
var db = Client.GetDatabase(databaseId);
var programContainer = db.GetContainer(containerId);
using FeedIterator<ProgramContainer> feedIterator = programContainer.GetItemLinqQueryable<ProgramContainer>()
.Where(x => studentIds.Contains(x.StudentId)).ToFeedIterator(); //Giving me error at studentIds.Contains Please find the error details below:
CS1929: Guid[] does not contain a definition for 'Contains' and the best extension method overload requires a receiver of type
ProgramContainer class for reference:
public class ProgramContainer
{
public string ProgramName{ get; set; }
public string ProgramCode { get; set; }
public Guid StudentId { get; set; }
public bool IsActive { get; set; }
}
Please assist.Thanks in Advance!!!
Try explicitly casting to guid
using FeedIterator<ProgramContainer> feedIterator =
programContainer.GetItemLinqQueryable<ProgramContainer>()
.Where(x => studentIds.Contains((Guid)x.StudentId)).ToFeedIterator();

How to put select query in a list in C#? I get an error

I'm trying to make a webpage in c# .net core razorpages. Basically I want the values of a specific column from my postgresql table in a list, and then show these values in the select option in html. But I'm having some problems on the c# side. I get this error:
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List<Project_Corona.Models.WorkspaceModel>' [Project_Corona]
Here is the code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Project_Corona.Database;
using Project_Corona.Models;
using Npgsql;
namespace Project_Corona.Controllers
{
public class HomeController : Controller
{
public IActionResult Employeepage()
{
var cs = Database.Database.Connector();
using var con = new NpgsqlConnection(cs);
con.Open();
List<WorkspaceModel> res = new List<WorkspaceModel>();
res = ("Select location FROM workspaces").ToList();
return View();
}
}
}
This is the code from WorkspaceModel.cs (if necessary)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Project_Corona.Database;
using Project_Corona.Models;
using Npgsql;
namespace Project_Corona.Models
{
public class WorkspaceModel
{
[BindProperty]
public string LocationName { get; set; }
[BindProperty]
public string RoomName { get; set; }
[BindProperty]
public int SquareMeters { get; set; } = 1;
[BindProperty]
public int Lengthws { get; set; } = 1;
[BindProperty]
public int Widthws { get; set; } = 1;
}
}
Have you tried to use EntityFramework Core for PostgreSQL to query your database?
I created a small example here
Simply create a DbContext with your database server settings:
public class WorkspaceContext : DbContext
{
public DbSet<WorkspaceModel> Workspaces { get; set; }
//protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseInMemoryDatabase("inmemory");
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseNpgsql("Host=my_host;Database=my_db;Username=my_user;Password=my_pw");
}
... and call container.AddDbContext<WorkspaceContext>(); in your Dependency Injection configuration.
Now you can query your underlying database very easy by calling:
var res = ctx.Workspaces.Select(w => w.LocationName);
// var res = ctx.Workspaces.FromSqlRaw("Select location FROM workspaces");
Then you will get the result according to your sql statement: Select location FROM workspaces

.Net Core API using Oracle database - How to choose return types and convert OracleCommand results into those types

I have spent more than 2 days now and I have not been able to find something that clearly explains how to create an API in .NET Core using an oracle database as I found very little information about this topic.
I ask for some patience, I'm a noob at .net core and oracle makes it harder for me to have to use Oracle Database.
I post this with hope that somebody will be able to guide me through this process.
I followed the next tutorial:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio
I could successfully create the API, the problem is that this API does not work with oracle database which is a requirement I cannot change.
So far what I have done is:
I created a .NET Core project and selected API
I created a Models Folder and created Employee class
Added OracleManagedDataAccessCore Nuget package
I created a Scaffold API controller (Empty)
I connected my api to oracle
My Employee Model code is the following:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace OracleAPI.Models
{
public class Employee
{
[Key]
public int EMPLOYEE_ID { get; set; }
[Required]
public string FIRST_NAME { get; set; }
[Required]
public string LAST_NAME { get; set; }
[Required]
public string EMAIL { get; set; }
[Required]
public string PHONE_NUMBER { get; set; }
[Required]
public string HIRE_DATE { get; set; }
public int JOB_ID{ get; set; }
public double SALARY { get; set; }
public double COMMISSION_PCT { get; set; }
public int MANAGER_ID { get; set; }
public int DEPARTMENT_ID { get; set; }
}
}
My API Controller looks something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OracleAPI.Models;
using Oracle.ManagedDataAccess.Client;
namespace OracleAPI
{
[Route("api/[controller]")]
[ApiController]
public class APIController : ControllerBase
{
public string conString = "User Id=HR;Password=HR;Data Source=localhost:1521/xe";
public static Oracle.ManagedDataAccess.Client.OracleConnection con;
public APIController()
{
con = new OracleConnection(conString);
}
//This is the part where Im stuck
[HttpGet]
public async Task<ActionResult<Employee>> GetEmployees()
{
using (con)
{
try
{
using (OracleCommand cmd = new OracleCommand())
{
con.Open();
cmd.BindByName = true;
cmd.CommandText = "SELECT * FROM employees";
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//await context.Response.WriteAsync("This part is obviously going to be removed but it's commented here to show why I chose this method to by an async task and this was in the example of the connection to the oracle database");
}
}
}
catch (Exception ex)
{
return null;
}
}
}
}
}
The problem basically comes when I have to choose a return type, I have tried using JSONResult but I have not managed to convert my reader result into Json, nor I have been able to use the same return types that are used in the tutorial when EntityFrameworkCore is used.
I hope you can guide me through the right path for understanding not only how to choose the right return type depending on what operation I'm performing (Create, Read, Update, Delete) (Post, Get, Put, Delete) and also how to be able to convert OracleCommand results into that return type.
Note: I use Oracle database 18c Express Edition and the purpose of creating the API is because I need to consume the API from a Xamarin project and since the oracle nuget is not available for iOS, the best bet for me is to create the API.
Thanks a lot in advanced. I will appreciate any help anyone can provide.

Unable to call "select" stored procedure using EF6 code first from database

This code is failing with the error: "Must declare the scalar value #prodID". Any suggestions?
using (var ctx = new StewieDataModel())
{
string productID = "81";
var techData = ctx.Database.SqlQuery<TechData>("dbo.usp_DS_GetTechData #prodID", productID).ToList();
}
Here's the model:
namespace DatasheetData
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class StewieDataModel : DbContext
{
public StewieDataModel()
: base("name=StewieConnectionString")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
}
Here's the class I want to populate:
namespace DatasheetData
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("usp_DS_GetTechData")]
public partial class TechData
{
public string TestCategory { get; set; }
public string TestName { get; set; }
public string TestResultLabel { get; set; }
public string TestResult { get; set; }
public string TestMethod { get; set; }
}
}
Here's how I call it successfully in SSMS:
DECLARE #return_value int
EXEC #return_value = [dbo].[usp_DS_GetTechData]
#prodID = "81"
SELECT 'Return Value' = #return_value
GO
The SSMS results are four columns of VarChar data:
You need to pass the parameter as a SqlParameter object. Something like this should work:
var techData = ctx.Database.SqlQuery<TechData>(
"dbo.usp_DS_GetTechData #prodID",
new SqlParameter("prodID", productID)
).ToList();
A shorthand alternative to DavidG's correct answer is:
var techData = ctx.Database.SqlQuery<TechData>(
"dbo.usp_DS_GetTechData #prodID = {0}", productID).ToList();
as explained here.

Add View - Cannot retrieve Metadata

I am still new to MVC, but I am starting to get a feel for the general picture however I still mixup things like namespace, or using and I THINK that may be the case here where I am mis-referencing something.
Question: I am trying to add an EmployeeInfo View, with a List template, with Model class: EmployeeInfo, with data context class: MoviesEntities
The auto-generation will not execute. When I right-click in Controller's method EmployeeInfo. I select the option "Add View", fill in the information, then hit add and during the scaffolding load screen it gives me the error as follows.
There was an error running the selected code generator: 'Unable to
retrieve metadata for 'WebApplication2.Models.EmployeeInfo'.'
My controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Entities;
using WebApplication2.Models;
namespace WebApplication2.Controllers
{
public class MoviesController : Controller
{
private MoviesEntities db = new MoviesEntities();
// GET: /Movies/
public ActionResult Index()
{
return View(db.Movies.ToList());
}
public ActionResult EmployeeInfo()
{
var query =
from m in db.Movies
join me in db.MovieEmployees
on m.ID equals me.movieID
join e in db.Employees
on me.employeeID equals e.ID
join r in db.Roles
on me.roleID equals r.ID
select new EmployeeInfo() {Name = e.Name, Role = r.RoleType, Birthday = e.Birthday };
return View(query.Distinct().ToList());
}
}
}
My context
//------------------------------------------------------------------------------
// <auto-generated> Built from database Movie </auto-generated>
//------------------------------------------------------------------------------
namespace WebApplication2.Entities
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using movieLayer;
using WebApplication2.Models;
public partial class MoviesEntities : DbContext
{
public MoviesEntities()
: base("name=MoviesEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Location> Locations { get; set; }
public virtual DbSet<Movie> Movies { get; set; }
public virtual DbSet<MovieEmployee> MovieEmployees { get; set; }
public virtual DbSet<Role> Roles { get; set; }
public virtual DbSet<Show> Shows { get; set; }
public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
public System.Data.Entity.DbSet<WebApplication2.Models.EmployeeInfo> EmployeeInfoes { get; set; }
}
}
Model of EmployeeInfo:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApplication2.Models
{
public class EmployeeInfo
{
public EmployeeInfo() { }
public string Name { get; set; }
public string Role { get; set; }
public DateTime Birthday { get; set; }
}
}
What I did to solve this issue that I encountered when adding a scaffolded view by right clicking the controller action was to leave the "Data context class" field blank.
I'm not entirely sure as to why this works but I found this method from ASP.NET forums.
Make sure you rebuild your solution first. If you just added a new class, the scaffolding engine may not actually know about it, yet, if the project hasn't compiled.
If that doesn't work, close Visual Studio and restart. I have seen the scaffolding stuff just go wonky for no good reason in VS2012, and a restart will usually fix it.
The problem was the EmployeeInformation was just a "template" for the controller to dump it's data into from the query for the View.
EmployeeInformation was not actually an existing table, thus I had to make a model i.e. EmpleeInfoModels to hold the data, that was then passed to my custom View.
Method
public ActionResult EmployeeInformation()
{
var query =
from m in db.Movies
join me in db.MovieEmployees
on m.ID equals me.movieID
join e in db.Employees
on me.employeeID equals e.ID
join r in db.Roles
on me.roleID equals r.ID
select new EmployeeInfoModels() { Name = e.Name, RoleType = r.RoleType, Birthdate = e.Birthday, eID = e.ID };
return View(query.Distinct().ToList().Distinct());
}
Model
namespace WebApplication2.Models
{
public class EmployeeInfoModels
{
public int mID { get; set; }
public int eID { get; set; }
public string Name { get; set; }
public string RoleType { get; set; }
public DateTime Birthdate { get; set; }
}
}
And my View just brought in
#model IEnumerable<WebApplication2.Models.EmployeeInfoModels>
Adding one more tip: you may have this error if you have any configSource attributes in any of the elements in your web.config. I commented out all of the elements that contained a configSource attribute and then ran the scaffolding again and it worked like a charm. Once it was finished, I uncommented the elements in the web.config and I was all set.
Check your DataContextClass Option in Add View Pop winow and then correct the ConnectionString when adding your View from Controller
Refer Screenshot
.

Categories