I have a WebApi OData API.
I want to perform some pagination. I have managed to fill the nextlink since it exists in OData.
public IQueryable<Product> Get(int min=0,int max=0)
{
this.Request.ODataProperties().NextLink = new Uri(Url.ODataLink(
new EntitySetPathSegment("Products"),
new KeyValuePathSegment(Microsoft.Data.OData.Query.ODataUriUtils.ConvertToUriLiteral("100", Microsoft.Data.OData.ODataVersion.V3))
));
///more code.....
}
The problem is that like I can set the NextLink i want to do the same with a PreviousLink (AtomPub)
Is that possible with OData?
How can I create that custom field?
Thanks in advance
Related
I use EF Core and SQL Server local for my ASP.NET Core backend. In SQL Server, I have a long complex parametizered stored procedure with multiple joins.
I call it like this:
[HttpGet("plantpl/{plantId}&{year}&{costAccTypeId}")]
public IActionResult GetPlantPl(long plantId, int year, long costAccTypeId)
{
SqlParameter plantIdParam = new SqlParameter("#PlantId", plantId);
SqlParameter yearParam = new SqlParameter("#Year", year);
SqlParameter costAccTypeIdParam = new SqlParameter("#CostAccTypeId", costAccTypeId);
var plantPLRows = DataContext.PlantPLRows.FromSqlRaw("PlantPl #PlantId, #Year, #CostAccTypeId",
plantIdParam, yearParam, costAccTypeIdParam);
return Json(plantPLRows);
}
In order to use the FromSqlRaw method, I had to create a model class PlantPLRow and the corresponding DbSet PlantPLRows.
Basically, I just want to get some data back from the database and send it to the client. I don't want a new DbSet nor migration for this. But to use the FromSqlRaw I have to use it.
So my question: is this the right way for my situation?
#Sergey, the API call, it's signature/attribute and the controller code are fine and reached, no need to change.
This blog post from #ErikEj gave the hint. I had to add this lines of code to my DataContext class:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PlantPLRow>().HasNoKey();
}
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?
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"
}
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/
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.
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.
I'm starting a new ASP.NET project after a few years developing in MVC4, and I have a question regarding architecture.
At the top corner of each page, I will display details of the current logged in user.
In MVC4 I achieved something like this by creating a BaseController, which created an EF data connection, and set up some common variables that would be used on every page - CurrentUser being one of them.
Now that I'm using Core, this approach doesn't seem to work, and certainly isnt mockable.
What would be the correct way to achieve something like this via ASP.NET Core?
I need the same variables on every view, and certainly dont want to have to write the code in each controller action!
You can use View Components feature in asp.net core to implement that functionality.
//In your ConfigureServices method , add your services that will be injected whenever view component is instantiated
public void ConfigureServices(IServiceCollection services) {
services.AddSingleton<IUserRespository, UserRepository>();
}
//Now Create a view component
public class LoggedInUser : ViewComponent
{
private IUserRespository userRepository;
//Services can be injected using asp.net core DI container
public LoggedInUser(IUserRepository userRepository,SomeOtherService service)
{
//assign services to local variable for use later
this.userRepository = userRepository;
}
//This method can take any number of parameters and returns view
public async Task<IViewComponentResult> InvokeAsync(int param1,string param2,etc )
{
//get the logged in user data here using available services
var loggedInUserData = GetSomeData(context);
return View(loggedInUserData );
}
}
Create view file # View/Shared/Components/LoggedInUser/Default.cshtml.View can be strongly typed.
#model LoggedInUserModel
<div>
<!-- html here to render model -->
</div>
Now, since you use to display this data on every page , you need to apply _Layout.chstml to all your pages . In the _Layout.chstml , you can render view component defined above with any additional parameter you would like to pass as anonymous type.
#await Component.InvokeAsync("LoggedInUser", new { param1=value,param2=value,etc })
Testing the View Component:
var mockRepository = Mock of ICityRepository;
var viewComponent= new LoggedInUser(mockRepository);
ViewViewComponentResult result
= viewComponent.Invoke() as ViewViewComponentResult; //using Invoke here instead of InvokeAsnyc for simplicity
//Add your assertions now on result
Note :
It is also possible to decorate a controller with [ViewComponent(Name = "ComponentName")] attribute and define public IViewComponentResult Invoke()
or public IViewComponentResult InvokeAsync() to turn them in to hybrid controller - view component.
I'm working on a new OData project, and am trying to do it with Web API 2 for the first time. The OData feed was pretty simple to put in place, which was great in comparison to WCF.
The problem I have now is that my OData feed will be used in a "multi-tenant" environment and I would like to use "friendly" URLs for the feed depending on the tenant. Therefore, I would ideally need the feed URLs to look like this:
/store/tenant1/Products
/store/tenant2/Products
Both URLs are pointing to the same controller and ultimately the same dataset, but I would like to enforce some entity filtering based on the tenant. Apparently this is going to be difficult and somewhat different to standard Web API routing since I can only specify a route prefix and not a route template.
So far, I've modified my OData controller to take the tenant name as a parameter and this works great when hitting the following url (which is not exactly what I want, see target above):
http://mydomainname/odata/Products?tenantName=test
Using this route definition:
ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Product>("Products");
IEdmModel model = modelBuilder.GetEdmModel();
config.Routes.MapODataRoute(routeName: "OData", routePrefix: "odata", model: model);
And this is the sample action on my controller:
[Queryable]
public IQueryable<Product> GetPproducts(string tenantName)
{
return _products.Where(p=>p.TenantName == tenantName);
}
I'm not quite sure if this is possible and my last resort will be to use URL rewrite rules, but I'd rather avoid this and have everything in code, done the right way.
Thanks a lot for your help!
After some investigation I found it works in this way: Just apply the route prefix name to the query, for example:
public class MoviesController : ODataController
{
private MoviesContext _db = new MoviesContext();
public IHttpActionResult Get()
{
var routeName=Request.ODataProperties().RouteName;
ODataRoute odataRoute=Configuration.Routes[routeName] as ODataRoute;
var prefixName = odataRoute.RoutePrefix;
return Ok(_db.Movies.Where(m=>m.Title.StartsWith(prefixName)));
}
// Other methods here
}
Note: The above code is based on ODataActionsSample in https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/
Now OData v4 has become a standard of OASIS, but v3 is not, so v4 seems a good start point.
I'm whondering, wheather there is an easy way to pupolate doctrine entities from request objects. I'm building a RESTful API with fos/rest-bundle, so I dont need forms.
Do you know a good way to do this, in a very easy and short way?
// POST /api/products
public function postProductsAction(Request $request)
{
$product = new Product();
}
In addition, I'm whondering wheather its possible to inject instances of entities directly in the controller with post requests.
// PUT /api/product/1
// I need this functionality for post requests too
public function putProductAction(Product $product)
{
return $product; // { "id" : "1", "name" : "foo" }
}
Greetings,
--marc
What you need is the most common goal of every REST API. And the best way to do this is to use a serializer, in addition to forms (even if you would prefere to not use forms).
I advise you to read for example this tutorial writen by William Durand. It explains every points very well and uses the JMSSerializerBundle to convert entities through the API.