25

I need to build a Web API from ASP.NET Core without Entity Framework. It's an existing database that has some custom stored procedures and we do not want to use EF.

I searched this topic and can't find anything about it, is this even possible?

5
  • 3
    EF Core isn't related to ASP.NET Core. So, yes.Just use ADO.NET Commented Nov 6, 2018 at 16:27
  • Yes it is possible. Entity framework is just a method of retrieving data and is separate to ASP.NET Core WebAPI Commented Nov 6, 2018 at 16:27
  • 2
    You can use any data access library you want, as long as it runs on .NET Core. Commented Nov 6, 2018 at 16:27
  • 9
    Every example I see is using EF Commented Nov 6, 2018 at 18:50
  • Are there any examples out there of this? Commented Nov 6, 2018 at 18:50

4 Answers 4

4

This is possible.

The first problem you will run into is getting the database connection string. You will want to import the configuration to do so. In a controller, it might look like this:

    private readonly IConfiguration _configuration;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

Add using System.Data and using System.Data.SqlClient (you'll need NuGet for SqlClient) as well as using Microsoft.Extensions.Configuration. With access to the database, you are writing code "old style", for example:

    [HttpGet]
    [Route("[controller]/movies")]
    public IEnumerable<Movie> GetMovies()
    {
        List<Movie> movies = new List<Movie>();

        string connString = ConfigurationExtensions.GetConnectionString(_configuration, "RazorPagesMovieContext");
        SqlConnection conn = new SqlConnection(connString);
        conn.Open();

        SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Movie", conn);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        DataTable dt = ds.Tables[0];
        sda.Dispose();

        foreach (DataRow dr in dt.Rows)
        {
            Movie m = new Movie
            {
                ID = (int)dr["ID"],
                Title = dr["Title"].ToString(),
                ReleaseDate = (DateTime)dr["ReleaseDate"],
                Genre = dr["Genre"].ToString(),
                Price = (decimal)dr["Price"],
                Rating = dr["Rating"].ToString()
            };
            movies.Add(m);
        }
        conn.Close();
        return movies.ToArray();
    }

The connection string name is in appsettings.json.

"ConnectionStrings": {
"RazorPagesMovieContext": "Server=localhost;Database=Movies;Trusted_Connection=True;MultipleActiveResultSets=true"
 }
Sign up to request clarification or add additional context in comments.

Comments

3

Yes it is possible. Just implement the API by yourself. Or here is also sample for the identity scaffold, without EF.

https://markjohnson.io/articles/asp-net-core-identity-without-entity-framework/

1 Comment

Thanks for this comment. EFCore is the next iteration, but it seems to do too much behind the scenes and it takes an absurd amount of time to troubleshoot, and makes way too many superfluous/redundant calls to the database(s). This, plus, the added overhead is horrible for microservices. I was called out for using ADO.Net until after a side-by-side comparison - my "primitive" method absolutely smoked the best EF could offer. no thanks
3

Just used Dapper as our ORM in a project rather than EF.

https://dapper-tutorial.net/

It is similar to ADO.Net, but it has some additionally features that we leveraged and it was really clean to implement.

Comments

1

I realize this is an old question, but it came up in a search I ran so I figured I'd add to the answers given.

First, if the custom stored procedures are your concern, you can still run them using Entity Framework's .FromSql method (see here for reference: https://www.entityframeworktutorial.net/efcore/working-with-stored-procedure-in-ef-core.aspx) The relevant info is found at the top of the page:

EF Core provides the following methods to execute a stored procedure:
1. DbSet<TEntity>.FromSql(<sqlcommand>)
2. DbContext.Database.ExecuteSqlCommand(<sqlcommand>)

If you are avoiding Entity Framework for other reasons, it's definitely possible to use any database connection method you want in ASP.NET Core. Just implement your database connection methods using whatever library is relevant to your database and set up your controller to return the data in whatever format you want. Most, if not all, of Microsoft's examples return Entity Framework entities, but you can easily return any data format you want.

As an example, this controller method returns a MemoryStream object after running a query against an MS SQL server (note, in most cases where you want data returned it's my understanding that it should be a "GET" method, not "POST" as is done here, but I needed to send and use information in the HttpPost body)

[HttpPost]
[Route("Query")]
public ActionResult<Stream> Query([FromBody]SqlDto content)
{
    return Ok(_msSqlGenericService.Query(content.SqlCommand, content.SqlParameters));
}

Instead of a MemoryStream, you could return a generic DataTable or a List of any custom class you want. Note that you'll also need to determine how you are going to serialize/deserialize your data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.