I'm in the process of learning ASP.net, specifically WebAPI and MVC. I'm using Visual Studio Community 2013, .NET 4.5, and C#. I'm a total newb so I'm actually going through this particular walkthrough to understand how things work:
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
It's been ok so far, but I want to move on to connecting a database to populate my dataset. I'm very familiar with using Firebird and was able to install Firebird as a dataprovider (through NuGet and installing the appropriate DDEX files). Unfortunately, I'm having difficulty understanding how to query the database and populate my array.
Basically, this is what my code looks like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using FirebirdSql.Data.FirebirdClient;
using System.Configuration;
using System.Collections;
namespace NBAPoolWebService.Controllers
{
public class UserController : ApiController
{
User[] users = new User[]
{
new User { ID = 1, CREATED=new DateTime(2011, 1, 12), ISACTIVE='Y', USERNAME="TEST1"},
new User { ID = 2, CREATED=new DateTime(2012, 2, 22), ISACTIVE='Y', USERNAME="TEST2"}
};
public IEnumerable<User> GetAllUsers()
{
return users;
}
public IHttpActionResult GetUser(int id)
{
var user = users.FirstOrDefault((p) => p.ID == id);
if (user == null)
{
return NotFound();
}
return Ok(user);
}
}
}
Currently, if I visit http://localhost/api/user, I get my list of test users via JSON (which is what I want).
What I'm hoping to understand is how to change the array that I set to come from my Firebird database (via an SQL query). I know how to get my query (select * from users), I have a valid connection (confirmed through visual studio) and I have seen some tutorials on how to use FBConnection.
What I'm having difficulty with is actually using the data from the query and populate the objects in the array.
Any help would be greatly appreciated. If you could tell me the piece of code that I need to enter, or point me to the right tutorials, or if you think I should be using a specific technology or methodology, that would be great.
What I'm trying really trying to accomplish/understand is how to create a Web service that responds with JSON and that is connected to a Firebird database.
Thanks in advance for any help!
I've learned a ton about .Net and Entity Framework by watching pluralsight videos. If you don't have an account with them, signing up for the trial would allow you to watch Entity Framework and Data Models. There is a module dedicated to Creating Database First Entity Data Models, which you may find useful.
After a bunch of research, I stumbled upon the following link:
[link]http://johntomaselli.blogspot.ca/2012/04/mvc-4-firebird-ef-41-and-database-first.html
So I deleted my existing User Controller and Model and created a new Model using ADO.NET Entity Data Model (named User).
From there, I used EF Designed from Database and used the connectionstring I created in my web.config.
From there it let me choose the database tables I wanted and built out a Model called User.edmx.
After that, I created a controller using Web API2 Controller with action, using Entity Framework.
This allowed me to choose a model class with the corresponding name.
At this point, I think I need to do some research on the Entity Framework but this at least allows me to create a web service that connects to the database.
Hopefully this helps other young newbs on their start with ASP.net, MVC, WebAPI, Entity Frameworks, and Firebird.
My next steps will be understand the User.edmx and if I should have created a model for all tables (instead of just one). Hopefully I understand that when I resarch the Entity Framework.
Related
I have used Glimpse before and really liked it so when this new project came up I went right to it. This time however I am using the EF plugin which is new to me. Further the project is broken up into different layers. Overall glimpse is working and it is just the SQL tab that is not active. Logging is turned on with no errors.
My Solution is like so:
VS 2015
Repository Project EF 6.0.0.0
Glimpse ADO 1.7.3.0
Glimpse Core 1.8.6.0
MVC & WebAPI Project MVC 5.2.3 WebApi
Glimpse ADO 1.7.3.0
Glimpse ASP.Net
Glimpse Core 1.8.6.0
Glimpse EF6 1.6.5
Glimpse MVC 5
So I am creating a manual SQL connection and most likely that is where my mistake is?
In the repository I establish my context like this:
public class PROJDataContext : DbContext, IPROJDataContext
{
public PROJDataContext() : base(PROJConnection, true)
{ }
private static GlimpseDbConnection PROJConnection
{
get
{
//glimpse wrapper
var conxSection = ConfigurationManager.ConnectionStrings["PROJData"];
return new GlimpseDbConnection(new SqlConnection(conxSection.ConnectionString));
}
}
When I fire up the project localhost the SQL tab is disabled. I am assuming this is because the db has not been accessed yet.
I browse to a page that passes request to WebApi. WebApi queries the repository. Data is retrieved from repository and sent back to WebApi which then passes it back to the MVC controller action which then returns a view showing the data.
Glimpse accurately tracks ALL of this except the db portion so any pointers would be greatly appreciated.
Update...when I wrote this up it was EOD Friday. Talking this through with a colleague today I think I realized the problem. My MVC app which has the Glimpse hooks does NOT call SQL instead it calls off to web api and web api calls the repository which has the Glimpse SQL hooks.
I have a C# project with EF code-first approach. The purpose is to do crud operations. My web app will be hosted under IIS under two folders
web app
WCF service
The application will pass user credentials to the WCF service and then to SQL Server database. Code first approach works well in this case.
READ scenario: the data needs to be filtered on the database level, not on application level. So I cannot directly call tables while querying SQL using EF. User will not have read access on the tables but only on views. The SQL views will have responsibility to filter the data and then pass to the service.
The question is how to proceed with EF code first approach in a way that I can leverage the benefits of EF migration s and then map the tables to the SQL views. Can anyone explain how to proceed with this read scenarios and best approach?
Entity Framework doesn't support mapping to Sql views but you can do the following:
Create an entity class that mapping your (sql) view structure.
Add a new empty migration using the add-migration -IgnoreChanges command since you don't want your entities to map to tables.
In this migration you can create (Up method) your Sql view.
It is important to note that you have to indicate the Sql view name in your entity ("view entity?") configuration (mapping) class:
public class FooConfiguration : EntityTypeConfiguration<Foo>
{
public FooConfiguration()
{
ToTable("ViewName");
HasKey(p => p.Id); // You also have to configure a key
}
}
This article from Julie Lerman could be interesting for you: https://msdn.microsoft.com/en-us/magazine/dn519921.aspx
I have a webapi for which I am trying to debug.
I use a generic repository structure so all my entity framework calls are made in a separate class library.
So my web Api post end point effectively just calls service.insert(entity). Where the generic insert is in the separate class library.
Logging is currently setup and working in the api. Now I want to log the insert Sql generated by entity framework in the parent applications text log file (as something strange is going on in the live environment)
How would I go about doing this please?
How to do this depends on what version of Entity Frameework you are using. In EF6 and later it is simple:
using (var context = new DataContext())
{
// log is a log4net logger
context.Database.Log = message => log.Debug(message);
// insert the entity
}
See this blog series for more information - part 3 shows an example of logging to NLog with a command interceptor - and this page for options relating to earlier versions of EF.
I have a newly created ASP.net MVC3 project with all the defaults. I am using the approach to build the database. I come from a PHP background and this is my first attempt at a ASP.net project.
I created a new model called "posts" and I want to link it to the built in accounts/users system that came with the default project.
Only signed in users can add posts, and I want to know what user added what post. I want to link the posts to a single user.
In PHP I would create a FK in the posts table to the users table "posts_id" and when a user adds a new post I would fill in that field with the users's id. But there does not seem to be a ID field in the account model.
Questions
How do I link a model to the default account system build in to ASP.net MVC3 using code first approach?
How do I query for user fields from a view in the post controller?
Links to a tutorials would work for me.
Thanks
FKs like posts_id is a database style reference. The object oriented way of representing that data is by giving the Account object a ICollection<Post> and by giving each Post object an Account reference field.
E.g.
public class Post
{
public Account Account { get; set; }
...
}
As for retrieving this data, I would suggest a repository-style service class which would be responsible for saving/loading objects to & from the DB. I am not sure exactly how the Account records get persisted in the template MVC app so I can't say how it would tie into that data. I have always used my own User DB table and thrown away all that build in Microsoft account stuff.
Good luck!
Can somebody please explain:
I am using MVC3/C#/Razor to build a project to get used to using MVC.
I am using the inbuilt account controller.
I am storing the account data in my local SQL database using Entity Framework to connect.
How can I easily generate interfaces for EF?
SO FAR I am using the plugin from: http://blog.johanneshoppe.de/2010/10/walkthrough-ado-net-unit-testable-repository-generator/#step1
This allows me to have an interface for my entities already created.
However, I know that I have to change my HomeController arguments to accept either the real repository or a fake one for testing.
I am completely lost!
Have a look at these. They will help and get you started :
http://www.asp.net/entity-framework/tutorials/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
http://msdn.microsoft.com/en-us/library/gg416511(VS.98).aspx
For dependency injection, you can follow these steps :
Install-Package Ninject.MVC3 with nuget to your ASP.NET MVC 3 project (if your app is on version 3). This will basically do everything.
Then have the following on your controller :
private IMyModelRepository _myrepo;
public HomeController(IMyModelRepository myrepo)
{
_myrepo = myrepo;
}
Go to NinjectMVC3.cs file inside App_Start folder and add the following code to inside RegisterServices method :
private static void RegisterServices(IKernel kernel) {
kernel.Bind<IMyModelRepository>().To<MyModelRepository >();
}
Fire up your app and you should be up and running.