405 Method Not Allowed - For Keyless entity types

EF Core model allows keyless entity types, which can be used to carry out database queries against data that doesn't contain key values. There are never tracked for changes in the DataBase Context and therefore are never inserted, updated or deleted on the database.

How to use this in your class. Let's say, you have a class named Share, you can place [Keyless] attributes on top of the class, and that's it!

using Microsoft.EntityFrameworkCore;

using System.ComponentModel;

using System.ComponentModel.DataAnnotations;


namespace AzureHostedApi

{

    [Keyless]

    public class Share

    {

        [DisplayName("Share Code")]

        [Required(ErrorMessage = "{0} is required")]

        [StringLength(10, MinimumLength = 3,

        ErrorMessage = "Share Code should be minimum 3 characters and a maximum of 10 characters")]

        [DataType(DataType.Text)]

        public string? ShareCode { get; set; }       


        [DisplayName("Share Name")]

        [Required(ErrorMessage = "{0} is required")]

        [StringLength(50, MinimumLength = 3,

        ErrorMessage = "Share Name should be minimum 3 characters and a maximum of 50 characters")]

        [DataType(DataType.Text)]

        public string? ShareName { get; set; }


        [DisplayName("Share Description")]

        [DataType(DataType.MultilineText)]

        public string? Description { get; set; }


        [DisplayName("Share Price")]

        [RegularExpression(@"^\$?\d+(\.(\d{2}))?$")]

        [Required(ErrorMessage = "{0} is required")]

        public decimal SharePrice {get; set; }

    }

}


Here is your DBContext class named ShareDBContext.

using Microsoft.EntityFrameworkCore;

namespace AzureHostedApi
{
    public class ShareDBContext: DbContext
    {

        public ShareDBContext(DbContextOptions<ShareDBContext> options)
        : base(options) { }

        public DbSet<Share> Shares => Set<Share>();
    }
}


Now, using the minimal API concept, try to implement a post method and try to call it. Below is your program.cs file where app.MapPost has been defined.


//minimal API Project

using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.DependencyInjection;

using AzureHostedApi;


var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ShareDBContext>(options => options.UseInMemoryDatabase("MyShare"));


var app = builder.Build();


app.MapGet("/", () => "Minimal API!");

app.MapGet("/shares", async (ShareDBContext db) =>

    await db.Shares.ToListAsync());


app.MapGet("/shares/ShareCode", async (string ShareCode, ShareDBContext db) =>

    await db.Shares.FindAsync(ShareCode)

        is Share shareList

            ? Results.Ok(shareList)

            : Results.NotFound());


app.MapGet("/shares/{price}", async (float price, ShareDBContext db) =>

    await db.Shares.FindAsync(price)

        is Share shareList

            ? Results.Ok(shareList)

            : Results.NotFound());


app.MapPost("/sharesitem", async (Share share, ShareDBContext db) =>

{

    db.Shares.Add(share);

    await db.SaveChangesAsync();

    return Results.Created($"/sharesitem/{share.ShareName}", share);

});

    return Results.NotFound();

});


app.Run();


Guess, what would happen? It is 405 Method Not Allowed  


Postman


One last important thing about DBContext. Kindly note DbContext is not thread-safe. Not to share the DBContext objects between threads. Ensure to await all async calls before start using context instance.

And always to dispose the DbContext after use as this ensure to free unmanaged resources.

Comments

Popular posts from this blog

How to fix Azure DevOps error MSB4126

SharePoint Admin Center

How to create Custom Visuals in Power BI – Initial few Steps