Handle Oracle Database Connection in Dapper - asp.net

I am trying to connect to the Oracle Database and trying to execute a query.
So below is my Model Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace TestAPI.Models
{
public class TestAPIModel
{
[Key]
public int PRIO_CATEGORY_ID { get; set; }
public int LANG_ID { get; set; }
public System.DateTime REC_DATE { get; set; }
public int REC_USER { get; set; }
public Nullable<int> RFCH_ID { get; set; }
public string DESCR { get; set; }
public string COL_DESCR { get; set; }
public string ROW_DESCR { get; set; }
public string ABBR { get; set; }
}
}
DBContext Class is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace TestAPI.Models
{
public class TestAPIContext: DbContext
{
public DbSet<TestAPIModel> details { get; set; }
}
}
Now trying to create the Controller with the Dapper, now the issue is in most of the forums it is trying to connect to SQL Database. I am trying to access Oracle DB and return the result in JSON format .So if I give
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using System.Web.Http.Description;
using TestAPI.Models;
using Dapper;
namespace TestAPI.Controllers
{
public class TestAPIModelsController : ApiController
{
// GET: api/TestAPIModels
public IQueryable<TestAPIModel> Getdetails(int id)
{
OracleConnection dbConn = new OracleConnection("DATA SOURCE=AX;PASSWORD=CM;PERSIST SECURITY INFO=True;USER ID=AB");
dbConn.Open();
var strQuery = #"Select PRIO_CATEGORY_ID as PRIO,LANG_ID as LANG, REC_DATE as REC, REC_USER as RECUSER, DESCR,COL_DESCR AS COL,ROW_DESCR as DROW,ABBR from STCD_PRIO_CATEGORY_DESCR where REC_USER = " +id;
retrun dbConn.Query<TestAPIModel>();
dbConn.Close();
}
}
}
It throws an error saying that the dbconn.Query is not in context and I also tried TestAPIContext.Init even that throws error. Can anyone please suggest me how to deal Oracle connection with the Dapper. I am new to ASP.NET and the Creating the services. kind of really stuck, any help is greatly appreciated.

You were not passing the SQL. Also, the explicit close is not needed. You can wrap the code in a using as under the hood SqlConnection.Dispose() calls the SqlConnection.Close().
Perhaps this a typo, but "retrun" should be "return". Connectionstring should be read from the app.config vs. hard coded and I'd also consider making 'id' a parameter.
using (var dbConn = new OracleConnection("DATA SOURCE=AX;PASSWORD=CM;PERSIST SECURITY INFO=True;USER ID=AB"))
{
dbConn.Open();
var strQuery = #"Select PRIO_CATEGORY_ID as PRIO,LANG_ID as LANG, REC_DATE as REC, REC_USER as RECUSER, DESCR,COL_DESCR AS COL,ROW_DESCR as DROW,ABBR from STCD_PRIO_CATEGORY_DESCR where REC_USER = " +id;
return dbConn.Query<TestAPIModel>(strQuery);
}

I could handle this, with the following solution:
1. Install Oracle.ManagedDataAccess.Core Package from nuget.
2. Write ConnectionString as follows:
Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=0.0.0.0)(PORT=1521))(CONNECT_DATA=(SID=sidName))); User Id=*****; Password=******;
PORT=1521 => Default port of Oracle is 1521, you can change it with your Oracle server port
0.0.0.0 => Oracle server IP or name
sidName => SidName of oracle server
3. C# snippet code:
protected IDbConnection GetChargingOracleDbConnection
{
get
{
var oracleConnection = new OracleConnection("OracleConnectionString");
oracleConnection.Open();
return oracleConnection;
}
}
var query = "SELECT Id, Name FROM Service";
using (var dbConnection = GetChargingOracleDbConnection)
{
return dbConnection.Query<MyModel>(query).ToList();
}

Related

.Net EntityFramework Core - SQLite Error 1: no such table

I am running into an issue where the code is unable to find my existing Sqlite database that is in the same folder as this code that is calling it. The error I am getting is, "SQLite Error 1 table does not exist." I know the table exists, it is just unable to find the path. What am I doing wrong?
Note: I am not creating a code first Sqlite database. This is opening an existing Sqlite database
DATABASE CONTEXT CODE
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWidget.Domain.Data
{
public static class MyWidgetService
{
public static void GetAll()
{
using var context = new MyWidgetContext();
if (context.Translations.Any())
{
var data = context.Widgets.ToList();
foreach (var widget in data)
{
Console.WriteLine(widget.ProductName);
}
}
else
{
Console.WriteLine("No widgets found");
}
}
}
}
**DATABASE SERVICE CODE
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using Microsoft.EntityFrameworkCore;
namespace MyWidget.Domain.Data
{
public class MyWidgetContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(connectionString: "Filename=./MyWidgetDB.db");
}
public DbSet<WidgetData> Widgets { get; set; }
}
public class WidgetData
{
public int Id { get; set; }
public string ProductName { get; set; }
}
}
I decided to go another direction and use Dapper and System.Data.Sqlite.Core. This video by Tim Corey perfectly explains how to implement it:
https://www.youtube.com/watch?v=ayp3tHEkRc0
This methodology works really well and am using it in my GitHub project:
https://github.com/encouragingapps/Blender3DReference
I had the same problem: SqliteException: SQLite Error 1: 'no such table: ScanFolders'. I used the SQLlite Browser to inspect the database in the debug folder and it had no tables. Checking the properties on the db was set to "Do Not Copy" I changed it to "Copy if Newer" and that fixed the issue for me.

(are you missing a using directive or an assembly reference?)

i am writing common business logic class in App_code folder for connecting to database using EFW.but showing the following error " Error 1 The type or namespace name 'job' could not be found"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace WebApplication6.App_Code
{
public class BlCommon
{
public List<job> GetJobs()
{
pubs2012Entities pubsobject = new pubs2012Entities();
var x = pubsobject.jobs.ToList<job>();
return x;
}
}
}
and class generated by EFW from jobs table is
namespace WebApplication6.App_Code
{
using System;
using System.Collections.Generic;
public partial class job
{
public short job_id { get; set; }
public string job_desc { get; set; }
public byte min_lvl { get; set; }
public byte max_lvl { get; set; }
}
}
Seem you dont have a reference to assembly wich contain mentioned class
Ok I got it:
Public List<job> GetJobs()
{
pubs2012Entities pubsobject = new pubs2012Entities();
var x = pubsobject.jobs.ToList<job>();
return x;
}
Click on Job, Move the mouse cursor over the blue dash that appear at the bottom of
job click Generate Class and then move your Job.cs code to your new job.cs class and
delete the old one.

Reading values from DBML(having stored procedure)

I have a dbml that has stored procedures dragged off.I have EmployeeModel class that has get and set propertise .
I have an interface IEmployee and a Repository Employee Repository that has the implementation of the methods.Please refer the code.In Stored procedure GetRoles i just have SELECT * FROM ROLE .
In repository how to loop through the resultset.Can i change ISingleResult to IMultipleResult in dbml designer file?
EmployeeModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcWebsite.Models
{
public class EmployeeModel
{
public int RoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public string TaskMark { get; set; }
public int RoleFlag { get; set; }
}
}
IEmployee:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcWebsite.Models;
namespace MvcWebsite.DAL
{
public interface IEmployees
{
IList<EmployeeModel> ListAll();
// void Save(EmployeeModel employ);
}
}
EmployeeRepository.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcWebsite.Models;
using System.Data.Linq;
namespace MvcWebsite.DAL
{
public class EmployeeRepository:IEmployees
{
private DataDataContext _dataContext;
public EmployeeRepository()
{
_dataContext = new DataDataContext();
}
public IList<EmployeeModel> ListAll()
{
//IMultipleResults result =_dataContext.GetRoleDetails();
//var Emps = result.GetResult(EmployeeModel);
List<EmployeeModel> emp = _dataContext.GetRoleDetails();
// foreach (GetRoleDetailsResult role in Emps)
// {
// role.Description=Emps.
// }
return Emps.ToList();
}
}
}
You can loop through the resultset as below:
List<EmployeeModel> employeeModels = new List<EmployeeModel>();
foreach (EmployeeModel employeeModel in _dataContext.GetRoleDetails())
{
employeeModels.Add(employeeModel);
}
Or you can use System.Linq.Enumerable class ToList<> method as below:
List<Product> products = context.GetProducts().ToList<Product>();
IMultipleResults is used when stored procedure is returning more than one result sets. However when you drop such procedures on to the designer, it doesn't generate IMultipleResults. For this you can change the designer generated code to use IMultipleResults as below:
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetCustomerAndProducts")]
[ResultType(typeof(Customer))]
[ResultType(typeof(Product))]
public IMultipleResults GetCustomerAndProducts()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((IMultipleResults)(result.ReturnValue));
}
However, it would overwrite your modifications when you do any changes in the designer because it would regenerate the code. To avoid this you can use partial classes.
Or you can also use SqlMetal tool. It is a command-line tool that generates code and mapping for the LINQ to SQL component of the .NET Framework. This tool generates IMultipleResults. You can get the details for this tool here:
http://msdn.microsoft.com/en-us/library/bb386987.aspx
Edited:
Repository functionality will be same regardless of you work in ASP.Net Mvc or WinForms or any other presentation layer.
You can change your repository function to below:
public List<EmployeeModel> ListAll()
{
return _dataContext.GetRoleDetails().ToList<EmployeeModel>();
}
Or:
public List<EmployeeModel> ListAll()
{
List<EmployeeModel> employeeModels = new List<EmployeeModel>();
foreach (EmployeeModel employeeModel in _dataContext.GetRoleDetails())
{
employeeModels.Add(employeeModel);
}
return employeeModels;
}

workflow toolbox not updated with new activity

I've added to the activity pack the following activity:
namespace TeamFoundation.Build.ActivityPack
{
using System;
using System.Activities;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Build.Client;
[BuildActivity(HostEnvironmentOption.Agent)]
public sealed class CheckSlothInitialized : CodeActivity
{
[RequiredArgument]
public InArgument<string> DbUser { get; set; }
[RequiredArgument]
public InArgument<string> DbPassword { get; set; }
[RequiredArgument]
public InArgument<string> DbServer { get; set; }
[RequiredArgument]
public InArgument<string> DbName { get; set; }
protected override void Execute(CodeActivityContext context)
{
string connString = String.Format(
"data source={0};Integrated Security=false;Initial Catalog={1};User ID={2};Password={3}",
DbServer, DbName, DbUser, DbPassword);
}
}
}
After that I compile it I can't find it in the toolbox. I'm going to choose items in the toolbox and choosing the dll of my activity, but even then I can't find it in the list of System.Activities Components.
Please follow these check points.
Clean and rebuild your solution.
If your activity is in independent project (activity library) and you are referring this activity in a project containg xaml or xamlx file make sure all referenced dll should be added in reference.
Try to add this activity as code behind in a workflow and execute it, is there any exception thrown?

Why isn't my Entity Framework Code First Pluralization working?

I'm using Entity Framework Code First. Usually I have no problem, but for a database I'm working with I keep getting errors that it can't find the table in the SQL Server database. Here is what my class looks like:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class CustomApp_User
{
[Key]
public int UserID { get; set; }
[MaxLength(50)]
public string Username { get; set; }
[MaxLength(250)]
public string Email { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
In the database I have a table called "CustomApp_Users" to match the above. Note it has the "s" at the end.
And then I have:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
public class CustomAppDB : DbContext
{
public DbSet<CustomApp_User> CustomApp_Users { get; set; }
}
I expected EF codefirst to pluralize so that it would find "CustomApp_Users" in the database since this is how it usually works. But instead I get the error:
Invalid object name 'dbo.CustomApp_User'.
It appears it's not pluralizing the table name. I can't figure out why. One thing different with this database is that the Primary Keys do not follow the normal convention so I use the [Key] annotation.
I do know that if I use the [Table] annotation for my class it will work:
[Table("CustomApp_Users")]
But, I'd like to find out why the pluralization is not working the way I thought it would.
That is because the PluralizationService in EF can not pluralize it. It returns the same string if you pass it "CustomApp_User". Unfortunately you can not customize this service. So you need to configure the table name explicitly.

Resources