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; }
}
}
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();
Comments
Post a Comment