Create Query without entity framework - asp.net-mvc

I have the following code, but I can’t work out what I need to put in place of the // before .AddObject(Model); and .SaveChanges(); to get the method to work. It’s a create query but I’ve only ever done this while using the Entity Framework before now, in this case I’m not using EF.
[HttpPost]
public ActionResult Registration(UserDetailModel Model)
{
if (ModelState.IsValid)
{
Model.UserNameFK = User.Identity.Name;
Model.CompanyName = "CompanyName";
Model.IEMI = "IEMI";
//.AddObject(Model);
//.SaveChanges();
return RedirectToAction("Registration", "Home");
}
return View(Model);
}
Am I close?
Cheers,
Mike.

I hope you know Entity Framework is an Object Relational Mapping framework for .NET.
Basically it creates entity classes that map up to your database and make it easy to perform Create/Read/Update/Delete operations without writing any SQL.
If you're not using Entity Framework, you could use another ORM like NHinbernate.
OR
You could use plain ADO.NET classes with SQL to write/read data to/from your database.
Ex: If you're using SQL Server you would use the System.Data.SqlClient namespace for writing to your SQL DB, see the SQLCommand class (Writing to other supported DB's work the same way)
You would do something like this with the function below it:
CreateCommand(//just as an example you can use values from your model in sql
"INSERT INTO Users(Name, CompnayName, IMEI,) VALUES ("
+ Model.UserNameFK +", val2, val3,...)",
"your connection string"
);
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
See this for more documentation.

Related

Connect Azure MI SQL View to MVC app as read only code first

One aspect of an ASP.net core (6) MVC app I am working on needs to query an SQL View that already resides in an Azure SQL MI.
I need to be able to query this SQL View to be able to retrieve the data based on user input but with the following conditions.
I cannot use Entity Framework.
The connection has to be read only.
This has to be database first.
As of yet I do not have access to this View or any of the tables it draws from. However I am expected to have code ready to plug a connection string into.
Unfortunately any resources I have been able to find don't seem to apply to my specific conditions. So any advice in what direction or approach would work best would be appreciated.
Those are by no means "silly" conditions. You didn't specify the language or the database but I'll make assumptions
I cannot use Entity Framework
Just use standard ado.net
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ado-net-code-examples#sqlclient
(I know that Link only answers are frowned upon)
The connection has to be read only.
Ensure that the account you connect under is read only. In SQL Server this is achieved by making you a member of the db_datareader group. This is something that should be enforced by the DBA that gives you an account
This has to be database first.
That's not really relevant. Just use the linked sample code to read from the existing view.
Literal copy paste of code at the link above:
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT ProductID, UnitPrice, ProductName from dbo.products "
+ "WHERE UnitPrice > #pricePoint "
+ "ORDER BY UnitPrice DESC;";
// Specify the parameter value.
int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#pricePoint", paramValue);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}

Web API in ASP.net C#

I want to create a web API controller that returns product details with id. Using stored procedure calls from a database class, not DB context. Sending Request with ID & getting a response with Jason's values.
I saw many examples but they are directly using stored procedures from the DB context. But I want to introduce a connection string & call that method in business class than a business class call to the controller with the response return.
Please help with a small example
Here is one example. You can choose between using SQL Command or SQL Adapter, try searching a little bit more about it.
Programming isn't only writing a code it's also googling for solutions.
// Setup connection string to access local SQL Server 2000
string connectionString = "server=localhost;" +
"database=Northwind;uid=sa;pwd=manager";
// Instantiate the connection, passing the
// connection string into the constructor
SqlConnection con = new SqlConnection(connectionString);
// Open the connection
con.Open();
// Create and execute the query
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers",con);
SqlDataReader reader = cmd.ExecuteReader();
// Iterate through the DataReader and display row
while(reader.Read()) {
Console.WriteLine("{0} - {1}",
reader.GetString(0), reader.GetString(1));
}
Source

How to initialize and persist Castle ActiveRecordStarter per session for multi tenancy apps?

I am using Castle ActiveRecord in my Asp.net / MVC 2 / Multi-tenancy application with SQL Server as my backend.
For every user logging in, the app loads the corresponding DB, dynamically at run time like below:
IDictionary<string, string> properties = new Dictionary<string, string>();
properties.Add("connection.driver_class", "NHibernate.Driver.SqlClientDriver");
properties.Add("dialect", "NHibernate.Dialect.MsSql2005Dialect");
properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
properties.Add("connection.connection_string", strDBConnection);
InPlaceConfigurationSource source = new InPlaceConfigurationSource();
source.Add(typeof(ActiveRecordBase), properties);
ActiveRecordStarter.Initialize(new System.Reflection.Assembly[] { asm1 }, source);
The strDBConnection string comes from another small database that holds the user info, corresponding DB, etc.
Scenario:
When a user logs in, his DB gets loaded, he can do his CRUD jobs -- No Probs !
Another user logs in (from another remote machine) his DB gets loaded -- No Probs !
Now, when the first user reads from DB, he sees new data from the second user's DB
My little understanding for this behavious is : ActiveRecordStarter is a Static object.
Could someone help me with a solution for this situation ?
The expected behaviour:
each user should access his own DB only, securely, in parallel / at the same time.
Thanks a lot !
ActiveRecordStarter.Initialize should only be called once in your app (in Application_Start in Global.asax).
To achieve what you want, create a class that inherits from NHibernate.Connection.DriverConnectionProvider:
public class MyCustomConnectionProvider : DriverConnectionProvider
{
protected override string GetNamedConnectionString(IDictionary<string, string> settings)
{
return string.Empty;
}
public override IDbConnection GetConnection()
{
// Get your connection here, based on the request
// You can use HttpContext.Current to get information about the current request
var conn = Driver.CreateConnection();
conn.ConnectionString = ... // Retrieve the connection string here;
conn.Open();
return conn;
}
}
Then set the connection.provider property to the name of your class:
properties.Add("connection.provider", "MyCompany.Domain.MyCustomConnectionProvider, MyCompany.AssemblyName");

How can I return IQueyrable DTO from Webapi Get so I can use Odata filters

I'm trying to use a Odata filters with ODP.net with Entity framework inside of web api project ASP.NET MVC 4.0 RC. I want to return an IQueryable of OwnDTO . I get an internal 500 error without any details. I know there is an error generation bug with webapi RC, but I dont think that bug is my issue.
Get http://localhost:51744/api/Owner called using Fiddler
[Queryable]
public IQueryable<OwnDTO> Get()
{
using (Entities context = new Entities())
{
var query = from item in context.Owners
select
new OwnDTO
{
Name = item.Name
};
return query.AsQueryable();
}
}
//very simple for example
public class OwnDTO
{
public string Name;
}
I do not want to have use my Oracle EF generated classes (DAO) to return from my Get, but I know I can if I replace EntityObject with a more friendly interface. If I return IEnumerable it works, but I want Odata filters.
Update incase someone wants a working example.. Automapper or simliar should be used in the linq and the context should injected.
[Queryable]
public IQueryable<OwnDTO> Get()
{
{
var query = from item in Hack._EFContext.Owners
select
new OwnDTO
{
Name = item.Name
};
return query.AsQueryable();
}
}
That works fine, but it looks like Odata is removed post RC. So I need to search down another path.
It does work in RC but perhaps not in RTM when it ships - not quite clear yet.
Your problem is that you are disposing your context since you are using a using block. So context get disposed before the data is retrieved.
So instead of using register your object for disposal at the end of request. Tugberk has a post here.

Web api not returning newly added records from EF 4.1 DbContext

I have a simple asp.net MVC4 / EF 4.1 project created with VS 2011, with a layer for my domain model and one for my database that contains the DbContext. I have one basic domain class called Batch and a BatchController with the standard CRUD functionality using Index / Create / Edit actions. I add two default records with the overridden Seed method. All this works fine I can add / edit / delete records using the out of the box MVC template:
public class BatchController : Controller
{
private readonly MyContext _context = new MyContext();
public ActionResult Index()
{
return View(_context.Batches.ToList());
}
[HttpPost]
public ActionResult Create(Batch batch)
{
if (ModelState.IsValid)
{
this._context.Batches.Add(batch);
this._context.SaveChanges();
return RedirectToAction("Index");
}
return View(batch);
}
}
I added a new MVC4 Web api project to the solution with the intention of exposing the domain object so the data can be retrieved via json. This uses an api controller that I've called BatchesController, and I added a reference to my domain and database layers. I have two Get() methods, one to return all Batches and one to return a single batch given an id. I'm using IIS Express to host the main MVC app and the Web api. To retrieve all the Batches I run this in a browser:
http://localhost:46395/api/batches
Here's my Web api Controller :
public class BatchesController : ApiController
{
private readonly MyContext _context;
public BatchesController()
{
_context = new MyContext();
}
// GET /api/batches
public IEnumerable<Batch> Get()
{
var batches = _context.Batches.ToList();
if (batches == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return batches;
}
// GET /api/batches/5
public Batch Get(int id)
{
var batch = _context.Batches.Find(id);
if (batch == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return batch;
}
}
My problem is that when I add a new record and try to retrieve it via a browser, only the existing records aded with the Seed method are returned - I can't get any newly added record to be returned. The DbContext seems to be caching the initial records and not going to the database to get the latest...how do I return newly added records?
Just to clear out the obvious, you have surely rewired to Web API project to point to the same database, right? Because by default Web API will attach its own SQL Compact DB. Meaning that you could effectively be using 2 separate databases
There is an answer, which It doesn't solve my problem:
http://www.strathweb.com/2012/03/serializing-entity-framework-objects-to-json-in-asp-net-web-api/
Also, there is a same question at here:
http://forums.asp.net/t/1814377.aspx/1?Web+api+not+returning+records+from+EF+4+1+DbContext
and I find this useful:
ASP.Net Web API showing correctly in VS but giving HTTP500
BUT THE POINT IS:
You can not send the proxy object to webapi serializer. So it should be project to a new dynamic class or a predefined class which there is no virtual (or maybe IList, ICollection,...).
// GET api/ProfileGame
public dynamic GetProfileGames()
{
return db.ProfileGames.Select(pg => new
{
...
}).AsEnumerable();
}

Resources