.NET: NpgsqlCommand to IQueryable - postgresql

Is there a way to create an IQueryable from an NpgsqlCommand?
Something like this:
using (var connection = new NpgsqlConnection(_connectionString))
{
connection.Open();
using (var cmd = new NpgsqlCommand("SELECT o.Id, o.Name FROM schema.blogs", connection))
var blogsQueryable = cmd.Execute<IQueryable<BlogViewModel>>;
}

Npgsql on its own is just an ADO.NET provider, and as such does not map rows to your own objects.
You should take a look at Entity Framework Core for a full O/RM, or at Dapper for a lighter solution.

Related

Mapping complex stored procedure with code first approach

Is it possible with Entity Framework code-first approach to map already created stored procedures?
For example I have a complex stored procedure and I want to map it with code first approach.
I will run the script for creating stored procedure using migration so the procedure will always available but how to map it with code first approach?
AFAIK, there's no built-in support to map the stored procedure in code-first. You have to manually call the procedure though you can map the results of the procedure using ObjectContext's Translate method.
E.g.
using (var db = new BloggingContext())
{
// If using Code First we need to make sure the model is built before we open the connection
// This isn't required for models created with the EF Designer
db.Database.Initialize(force: false);
// Create a SQL command to execute the sproc
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "[dbo].[GetAllBlogsAndPosts]";
try
{
db.Database.Connection.Open();
// Run the sproc
var reader = cmd.ExecuteReader();
// Read Blogs from the first result set
var blogs = ((IObjectContextAdapter)db)
.ObjectContext
.Translate<Blog>(reader, "Blogs", MergeOption.AppendOnly);
foreach (var item in blogs)
{
Console.WriteLine(item.Name);
}
// Move to second result set and read Posts
reader.NextResult();
var posts = ((IObjectContextAdapter)db)
.ObjectContext
.Translate<Post>(reader, "Posts", MergeOption.AppendOnly);
foreach (var item in posts)
{
Console.WriteLine(item.Title);
}
}
finally
{
db.Database.Connection.Close();
}
}
You can also map the stored procedure that returns more complex type, if you're using an .EDMX file. See this MSDN article for more details.
Note: you can add T4 template to add the custom mapping to add the custom stored procedure mapping every time the .EDMX is generated.

Where is CreateQuery in Entity Framework 6

Simple question - where is dbContext.CreateQuery method in Entity Framework 6 and if the answer is there is not such method my question is what to do to get some data by SQL query to an objectQuery?
Cast context to IObjectContextAdapter and use ObjectContext, e.g.:
using (var context = new AdventureEntities())
{
string eSql = "SELECT VALUE c FROM AdventureEntities.Customer AS c ORDER BY c.LastName";
var query = ((IObjectContextAdapter)context).ObjectContext.CreateQuery<Customer>(eSql);
var customers = query.ToList();
foreach (Customer customer in customers)
{
Console.WriteLine("{0}, {1}", customer.FirstName, customer.LastName);
}
}

Reporting Services using Entity Framework

I had experience in developing reports(SSRS) using ado.net dataset. Now I am working on an application which is not using ADO.net but entity framework but entity framework does not return datatable or dataset. I want to know
Is there any way to use Collection or custom objects return by entity framework in the reporting services?
Entity framework somehow return datatable or dataset.
Or I should create datatable/dataset from the collection returned by entity framework manually.
For the record, I am getting resultset by executing stored procedure from entity framework.
public void getMyReportData()
{
using (myEntityDataModel v = new myEntityDataModel())
{
var reportQuery = (from r in v.myTable
select new
{
l.ID,
l.LeaveApplicationDate,
l.EmployeeNumber,
l.EmployeeName,
l.StartDate,
l.Col1,
l.Col2,
.......,
.......,
l.Address
}).ToList();
reportViewer1.LocalReport.DataSources.Clear();
ReportDataSource datasource = new ReportDataSource("nameOfReportDataset", reportQuery);
reportViewer1.LocalReport.DataSources.Add(datasource);
Stream rpt = loadEmbededReportDefinition("Report1.rdlc");
reportViewer1.LocalReport.LoadReportDefinition(rpt);
reportViewer1.RefreshReport();
//Another way of setting the reportViewer report source
string exeFolder = Path.GetDirectoryName(Application.ExecutablePath);
string reportPath = Path.Combine(exeFolder, #"rdlcReports\Report1.rdlc");
reportViewer1.LocalReport.ReportPath = reportPath;
reportParameter p = new ReportParameter("DeptID", deptID.ToString());
reportViewer1.LocalReport.SetParameters(new[] { p });
}
}
public static Stream loadEmbededReportDefinition(string reportName)
{
Assembly _assembly = Assembly.GetExecutingAssembly();
Stream _reportStream = _assembly.GetManifestResourceStream("ProjectNamespace.rdlcReportsFolder." + reportName);
return _reportStream;
}
Original source: Creating Reports in ASP.Net with Entity Framework

Does ria services have something like sqlclient SqlCommand for executing T-SQL?

How would ria services do this kind of thing?
using (SqlConnection connection = new SqlConnection(connectionString))
{
string TSQL="update products set price=price*1.03 where category='computer books'";
SqlCommand command = new SqlCommand(TSQL, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
Thanks, Mark
You need get all entites of Product with category computer books and then update price for them and save changes to DB.

Running sql in entity framework?

Is there any way to run a sql statement straight from the entity framework generated calls? Or will I have to create a procedure then call that via the entity framework?
Was Googling around for this myself the other day, this is the example I found hope it helps
static void ExecuteSql(ObjectContext c, string sql)
{
var entityConnection = (System.Data.EntityClient.EntityConnection)c.Connection;
DbConnection conn = entityConnection.StoreConnection;
ConnectionState initialState = conn.State;
try
{
if (initialState != ConnectionState.Open)
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close();
}
}
In EF 4.0 this is pretty easy because there are new methods on the ObjectContext that allow you to execute store commands (i.e. SQL) directly:
See this: ExecuteStoreCommand
If you are still using EF 3.5 SP1 you can still execute a query directly against the database if you really want to like this:
var econn = ctx.Connection as EntityConnection;
var dbconn = econn.StoreConnection;
at this point you have access to a connection (dbconn) to the underlying database, so you can use normal ADO.NET code to execute queries etc.
Hope this helps
Alex
ExecuteStoreQuery<> and ExecuteStoreCommand is what you want:
using (NorthWindEntities ctx = new NorthWindEntities())
{
ctx.ExecuteStoreQuery<>()
ctx.ExecuteStoreCommand();
}
#Alex James, out of curiosity, would this be efficient to run a full text sql bit of code, as in there should be no performance overhead right? To say, running the same full text sql code straight as a query in sql management studio.