2
votes

after followed the tutorial following these links:

https://devblogs.microsoft.com/odata/asp-net-core-odata-now-available/

https://devblogs.microsoft.com/odata/asp-net-odata-8-0-preview-for-net-5/

Everything worked fine with Microsoft.EntityFrameworkCore.InMemory. However, when I changed to SQL connections. The odata return 404 status when I tried to access http://localhost:57354/odata/Users enter image description here Here is my file conguration:

Startup.cs:

 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<DataContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<User, Role>()
                 .AddEntityFrameworkStores<DataContext>()
                 .AddDefaultTokenProviders();

        services.AddControllers();
        services.AddOData(opt => 
            opt.AddModel("odata", GetEdmModel())
           .Select().Filter().Count().Expand().OrderBy());
        services.AddScoped<IDataContext, DataContext>();
        services.AddTransient<DbContext, DataContext>();
        services.AddTransient<IUnitOfWorkAsync, UnitOfWork>();
        services.AddTransient<IUserService, UserService>();
        services.AddTransient(typeof(IRepository<>), typeof(Repository<>));
        services.AddTransient(typeof(IRepositoryAsync<>), typeof(Repository<>));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseODataBatching();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
    private static IEdmModel GetEdmModel()
    {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<User>("Users");
       
        return builder.GetEdmModel();
    }
}

My UserController.cs

 [Route("api/[controller]")]
[ApiController]
public class UsersController : ODataController
{
    private readonly IUnitOfWorkAsync _unitOfWorkAsync;
    private readonly IUserService _userService;
    public UsersController(
        IUserService userService,
        IUnitOfWorkAsync unitOfWorkAsync
    )
    {
        _userService = userService;
        _unitOfWorkAsync = unitOfWorkAsync;
    }

    [HttpGet]
    [EnableQuery]
    public async Task<IQueryable<UserViewModel>> Get()
    {
        return await _userService.GetAllUserAsync();
    }
    [HttpPost]
    public async Task<IActionResult> Post(UserViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        try
        {
            var user = await _userService.InsertUserAsync(model);
            _unitOfWorkAsync.Commit();
            var returnUser = new UserViewModel()
            {
                Id = user.Id,
                PhoneNumber = user.PhoneNumber,
                Email = user.Email,
                IsBanned = user.IsBanned
            };
            return Created("Created new user", returnUser);
        }
        catch (Exception ex)
        {

            throw;
        }
    }

    [HttpPut]
    public async Task<IActionResult> Put(UserViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        try
        {
            await _userService.UpdateUserAsync(model);
            _unitOfWorkAsync.Commit();
            await TryUpdateModelAsync(model);
            return Content("Updated User", "application/json", Encoding.UTF8);
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    [HttpDelete]

    public IActionResult Delete([FromODataUri] Guid key)
    {
        _userService.Delete(key);
        _unitOfWorkAsync.Commit();
        return StatusCode(200, new { Deleted = "Success" });

    }
}

Here what I've tried but It'd not been working yet so far.

  1. I tried to change in Startup.cs

    public void ConfigureServices(IServiceCollection services) {

         //Code keep the same
         services.AddControllers(mvcOptions => mvcOptions.EnableEndpointRouting = false);
         services.AddMvc();
         //Code keep the same.......
     }
    

and in Configure part I also changed to like .net Core 3.1 and earlier. However, the notification told me there is no method or member to implement these:

  app.UseMvc(routeBuilder =>
  {
      routeBuilder.EnableDependencyInjection();
      routeBuilder.Select().Filter().Count().Expand().OrderBy().MaxTop(null);
      routeBuilder.MapODataServiceRoute("odata", "odata", GetEdmModel());
  });

enter image description here

Then I also tried to add by another way in Configure but the same result:

  app.UseEndpoints(endpoints =>
  {
      endpoints.MapControllers();
      endpoints.MapODataRoute("odata1", "odata", GetEdmModel());
   });

enter image description here

I don't know how it's worked perfectly on the Microsoft.EntityFrameworkCore.InMemory library but somehow when I changed to SQL server everything is not run as I expected. Here is my file appsettings.json in case you want to know:

{ 
   "ConnectionStrings": {
   "DefaultConnection": "Server(localdb)\\mssqllocaldb;Database=basenetcore;Trusted_Connection=True
     ;MultipleActiveResultSets=true"
    },
    "Logging": {
    "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
     }
   },
  "AllowedHosts": "*"
}

Thank you for your time and I hope you have a good day.

1
By the way, I'm using odata as following this link: nuget.org/packages/Microsoft.AspNetCore.OData I'm using version 8.0-previewPhil Tran

1 Answers

1
votes

Just remove the code:

[Route("api/[controller]")]
[ApiController]

on your UsersController.