EF 7 on .NET 7 Geometry' property 'XXXXX.GeoLocation' could not be mapped because the database provider does not support this type - c#

I have a simple query
userloc = _dbContext.UserBrowsingLocationData.Where(c => c.IpAddress.Trim().ToLowerInvariant() == iPAddress.Trim().ToLowerInvariant())
which throws the following error.
UserBrowsingLocationData table does not have any geometry field nor does this table has any foreign key relationship.
I do have another table in the database which has geometry field, but that table is not begin referred directly or indirectly in the above query
What is the way out, I see that i can set it to not Mapped, but i would have to do that every time i regenerate model from db, i am doing reverse engineering from db ?
what would the converter look like since i am only interested in latitude and longitude from geometry field. I am storing latitude and longitude as geometry because i do search by radius in the query itself.
System.InvalidOperationException
HResult=0x80131509
Message=The 'Geometry' property 'XXXXXXXXXX.GeoLocation' could not be mapped because the database provider does not support this type. Consider converting the property value to a type supported by the database using a value converter. See https://aka.ms/efcore-docs-value-converters for more information. Alternately, exclude the property from the model using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
Source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ThrowPropertyNotMappedException(String propertyType, IConventionEntityType entityType, IConventionProperty unmappedProperty)
at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ThrowPropertyNotMappedException(String propertyType, IConventionEntityType entityType, IConventionProperty unmappedProperty)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidatePropertyMapping(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal.SqlServerModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelRuntimeInitializer.Initialize(IModel model, Boolean designTime, IDiagnosticsLogger`1 validationLogger)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, ModelCreationDependencies modelCreationDependencies, Boolean designTime)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel(Boolean designTime)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__8_4(IServiceProvider p)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
at Microsoft.EntityFrameworkCore.DbContext.get_Model()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.CheckState()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
at XXXXXX.BlazorServer.Services.UtilityClass.GetLocationByIdFromDB(String iPAddress, String userID) in C:\XXXXXXXXX\BlazorServer\Services\UtilityClass.cs:line 163
This exception was originally thrown at this call stack:
[External Code]
XXXXXX.BlazorServer.Services.UtilityClass.GetLocationByIdFromDB(string, string) in UtilityClass.cs
I am using Blazor Server and in the program.cs i configure the database as shown below
builder.Services.AddDbContext<XXXXXXDBContext>(options =>
{
//options.UseLoggerFactory(MyDBLoggerFactory);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
options.UseSqlServer(connectionString,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
sqlOptions.UseNetTopologySuite();
});
options.EnableSensitiveDataLogging();
options.EnableDetailedErrors();
options.LogTo(Console.WriteLine);
});
UserBorwsingLocationData Class
public partial class UserBrowsingLocationData
{
public Guid UserBrowsingDataID_PK { get; set; }
public Guid? UserID_FK { get; set; }
public string CountryCodeISO2 { get; set; }
public string CountryName { get; set; }
public string StateName { get; set; }
public string StateCode { get; set; }
public string CityName { get; set; }
public string PostalCode { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string JSONOutPut { get; set; }
public string IpAddress { get; set; }
public string TimeZone { get; set; }
public string DeviceName { get; set; }
public string OS { get; set; }
public DateTime? DateTime { get; set; }
public string CaptureMode { get; set; }
public string ApiUsedToGetData { get; set; }
public string LocationFromIPOrLatLong { get; set; }
public virtual User_M UserID_FKNavigation { get; set; }
}

Related

I'm adding an Entity (Category) as a property in another Entity (Product). System.ArgumentException: An item with the same key has already been added

In my API project, there is the entity Category as below:
[Key]
public string Id { get; set; }
public string Title { get; set; }
public Category(string id, string title)
And the Entity Product where Category is a property:
[Key]
public string Id { get; set; }
[Required(ErrorMessage = "Título é obrigatório.")]
[MaxLength(60, ErrorMessage = "Este campo deve conter enre 3 e 60 caracteres.")]
[MinLength(3, ErrorMessage = "Este campo deve conter enre 3 e 60 caracteres.")]
public string Title { get; set; }
[MaxLength(1024, ErrorMessage = "Este campo deve ter no máximo 1024 caracteres")]
public string Description { get; set; }
[Required(ErrorMessage = "Este campo é obrigatório")]
[Range(1, int.MaxValue, ErrorMessage = "O preço deve ser maior que zero")]
public decimal Price { get; set; }
public int AvailableQuantity { get; set; }
[Required(ErrorMessage = "Este campo é obrigatório")]
public string CategoryId { get; set; }
public Category Category { get; set; }
This is the Create Method in the ProductController:
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult<Product>> Create([FromBody] Product model)
{
var category = _context.Categories.AsNoTracking().FirstOrDefault(x => x.Id == model.CategoryId);
if (category == null)
return Ok("Categoria informada não existe");
if (ModelState.IsValid)
{
_product.GenerateId(model);
var product = new Product(model.Id, model.Title, model.Description, model.Price, model.CategoryId, category);
_context.Products.Add(product);
await _context.SaveChangesAsync();
return product;
}
else
{
return BadRequest(ModelState);
}
}
When I try to create a new Product I receive the error message as below:
System.ArgumentException: An item with the same key has already been added. Key: 280CF21D
at System.Collections.Generic.Dictionary2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) at System.Collections.Generic.Dictionary2.Add(TKey key, TValue value)
at Microsoft.EntityFrameworkCore.InMemory.Storage.Internal.InMemoryTable1.Create(IUpdateEntry entry) at Microsoft.EntityFrameworkCore.InMemory.Storage.Internal.InMemoryStore.ExecuteTransaction(IList1 entries, IDiagnosticsLogger1 updateLogger) at Microsoft.EntityFrameworkCore.InMemory.Storage.Internal.InMemoryDatabase.SaveChangesAsync(IList1 entries, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList1 entriesToSave, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(DbContext _, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at TesteAPI.Controllers.ProductsController.Create(Product model) in C:\Users\tcho3\source\repos\TesteAPI\TesteAPI\Controllers\ProductsController.cs:line 93 at lambda_method56(Closure , Object ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
fix model
public class Category
{
[Key]
public string Id { get; set; }
public string Title { get; set; }
.....
public virtual ICollection<Product> Products { get; set}
}
You don't need a special constructor for Product too since you are using Product as a model
fix your action
public async Task<ActionResult<Product>> Create([FromBody] Product model)
{
//---------- I don't think that you really need this
var category = _context.Categories.AsNoTracking().FirstOrDefault(x => x.Id == model.CategoryId);
if (category == null) return Ok("Categoria informada não existe");
//---------
//would be enough
if (model.category == 0) return Ok("Categoria informada não existe");
if (ModelState.IsValid)
{
_product.GenerateId(model);
_context.Products.Add(model;
await _context.SaveChangesAsync();
return model;
}
else
{
.....
}
}
yes because the Category already exist in the database so that the category to be related to the product you just need to pass the CategoryId when you create the Product like the Following :
var product = new Product(model.Id, model.Title, model.Description, model.Price, model.CategoryId);
no need to pass category object.

ASP.NET Core 5 Web API, POST return CreatedAtAction error

I am using .NET version 5.0.100-preview.8.20417.9 . What is wrong at here:
return CreatedAtAction(nameof(TrustedPerson), new { id = item.Id }, TrustedPerson(item));
Model
using System;
#nullable disable
namespace shadow.Models
{
public partial class TrustedPerson
{
public int Id { get; set; }
public string Fullname { get; set; }
public string AliasName { get; set; }
public string Email { get; set; }
public string PhoneNumber1 { get; set; }
public string PhoneNumber2 { get; set; }
public string PhoneNumber3 { get; set; }
public int? RelationshipId { get; set; }
public string About { get; set; }
public int? AvatarId { get; set; }
public DateTime? Created { get; set; }
public DateTime? Modified { get; set; }
}
}
File TrustedPersonController
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using shadow.Data;
using shadow.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace shadow.Controllers
{
[ApiController]
[Route("[controller]")]
public class TrustedPersonController : ControllerBase
{
private readonly ApplicationDbContext _db;
public TrustedPersonController(ApplicationDbContext context) : base()
{
this._db = context;
}
/// <summary>
/// UserId = id của người dùng chính.
/// </summary>
/// <param name="UserId"></param>
/// <returns></returns>
[HttpGet]
[Route("all")]
public ActionResult GetAllTrustedPersons(string UserId)
{
var list = from trustedPerson in _db.TrustedPeople
join userTrustedPerson in _db.UserTrustedPeople on trustedPerson.Id equals userTrustedPerson.TrustedPersonId
// join user in db.Users on User.Identity.Id
where userTrustedPerson.UserId == UserId
select trustedPerson;
return Ok(list.ToList());
}
[HttpPost]
public async Task<ActionResult<TrustedPerson>> AddTrustedPersons(TrustedPerson trustedPerson)
{
var item = new TrustedPerson
{
Fullname = trustedPerson.Fullname,
About = trustedPerson.About,
AliasName = trustedPerson.AliasName,
AvatarId = trustedPerson.AvatarId,
Created = DateTime.Now,
Email = trustedPerson.Email,
PhoneNumber1 = trustedPerson.PhoneNumber1,
PhoneNumber2 = trustedPerson.PhoneNumber2,
PhoneNumber3 = trustedPerson.PhoneNumber3,
RelationshipId = trustedPerson.RelationshipId
};
_db.TrustedPeople.Add(item);
await _db.SaveChangesAsync();
return CreatedAtAction(nameof(TrustedPerson), new { id = item.Id }, TrustedPerson(item));
}
}
}
Error
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://0.0.0.0:5002
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: D:\shadow_backend
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data, this mode should only be enabled during development.
warn: Microsoft.EntityFrameworkCore.Model.Validation[30000]
No type was specified for the decimal column 'Id' on entity type 'Topic'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()' or specify a ValueConverter.
warn: Microsoft.EntityFrameworkCore.Model.Validation[30000]
No type was specified for the decimal column 'PublisherId' on entity type 'Topic'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()' or specify a ValueConverter.
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: No route matches the supplied values.
at Microsoft.AspNetCore.Mvc.CreatedAtActionResult.OnFormatting(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsyncCore(ActionContext context, ObjectResult result, Type objectType, Object value)
at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsync(ActionContext context, ObjectResult result)
at Microsoft.AspNetCore.Mvc.ObjectResult.ExecuteResultAsync(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultAsync(IActionResult result)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
D:\shadow_backend\bin\Debug\net5.0\shadow.exe (process 13440) exited with code -1.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .
As Kirk Larkin says,the first parameter is action name,you can refer to this.Here is a demo worked:
public class Item {
public int Id { get; set; }
}
[Route("TrustedPerson")]
public IActionResult TrustedPerson(int id)
{
return Ok();
}
[Route("TestCreatedAtAction")]
public IActionResult TestCreatedAtAction() {
Item item = new Item { Id = 1 };
return CreatedAtAction("TrustedPerson", new { id = item.Id }, item);
}
or you can use return CreatedAtAction(nameof(TrustedPerson), new { id = item.Id }, item);

Input string was not in a correct format EF6

I am currently using EF6 and trying to implement a one-to-many relationship using code-first:
public class Schedule
{
public int ScheduleId { get; set; }
}
public class Instruction
{
public int Id { get; set; }
public Schedule Schedule { get; set; }
}
I am following convention 1 here.
In my method i first try to add an empty schedule:
public class ScheduleRepo {
public void SetSchedule()
{
Schedule schedule = new Schedule();
using (UptrenderDbContext ctx = new UptrenderDbContext())
{
ctx.Schedules.Add(schedule);
ctx.SaveChanges();
}
}
}´
The method is called from a test:
[TestFixture]
public class ScheduleRepoTest {
private readonly ScheduleRepo repo = new ScheduleRepo();
[Test]
public void TestSetSchedule()
{
repo.SetSchedule();
}
}
My context looks like this:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class UptrenderDbContext : DbContext
{
public DbSet<Schedule> Schedules { get; set; }
public DbSet<Instruction> Instructions { get; set; } //Not used yet
public UptrenderDbContext () {
Database.SetInitializer(new DropCreateDatabaseAlways<UptrenderDbContext >());
}
}
When running the program i get the stack trace:
Stack trace:
System.FormatException : Input string was not in a correct format.
at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.Convert.ToDouble(String value)
at MySql.Data.Entity.MySqlMigrationSqlGenerator.Generate(CreateIndexOperation op)
at MySql.Data.Entity.MySqlMigrationSqlGenerator.Generate(IEnumerable`1 migrationOperations, String providerManifestToken)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
at System.Data.Entity.DropCreateDatabaseAlways`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at Data.Repos.Impl.ScheduleRepo.SetSchedule() in C:\Users\Benjamin\Desktop\uptrender\Data\Repos\Impl\ScheduleRepo.cs:line 20
at Data.Tests.ScheduleRepoTest.TestSetSchedule() in C:\Users\Benjamin\Desktop\uptrender\Data\Tests\ScheduleRepoTest.cs:line 21
I notice that if i remove public Schedule Schedule{ get; set; } from Instruction no exception is thrown and schedule is successfully added to the db.
I probably missed something very trivial here because im new to EF6.

Null reference on creating table with foreign key in Umbraco on application start

I am using Umbraco 7.2.1 and wanted to create table on application start. There are two tables project and students, classes are as follows.
[TableName("Projects")]
public class Project
{
[PrimaryKeyColumn(AutoIncrement=true)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
and
[TableName("Students")]
public class Student
{
[PrimaryKeyColumn(AutoIncrement=true)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[ForeignKey(typeof(Project))]
public int ProjectId { get; set; }
}
On Application start I am checking if these table exists and if not creating them as below
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
var db = applicationContext.DatabaseContext.Database;
//Check if the DB table does NOT exist
if (!db.TableExist("Projects"))
{
//Create DB table - and set overwrite to false
db.CreateTable<Project>(false);
}
if (!db.TableExist("Students"))
{
//Here is the problem
//If Student table do not contain foreign key, it works fine
db.CreateTable<Student>(false);
}
base.ApplicationStarted(umbracoApplication, applicationContext);
}
Now, the first table is created properly without any error, but when it reaches for second table(Students) there is a null reference error, I know this is due to the foreign key I have used, but do not know how to solve this. Stack trace is as below
[NullReferenceException: Object reference not set to an instance of an object.]
Umbraco.Core.Persistence.DatabaseModelDefinitions.DefinitionFactory.GetForeignKeyDefinition(Type modelType, PropertyInfo propertyInfo, ForeignKeyAttribute attribute, String columnName, String tableName) +203
Umbraco.Core.Persistence.DatabaseModelDefinitions.DefinitionFactory.GetTableDefinition(Type modelType) +754
Umbraco.Core.Persistence.PetaPocoExtensions.CreateTable(Database db, Boolean overwrite, Type modelType) +100
Umbraco.Core.Persistence.PetaPocoExtensions.CreateTable(Database db, Boolean overwrite) +121
ChatUmbraco.App_Code.UmbracoStartup.ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) in d:\ECM\Projects\Umbraco\ChatUmbraco\ChatUmbraco\App_Code\UmbracoStartup.cs:44
Umbraco.Core.ApplicationEventHandler.OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) +62
Umbraco.Core.CoreBootManager.<Complete>b__5(IApplicationEventHandler x) +79
Umbraco.Core.EnumerableExtensions.ForEach(IEnumerable`1 items, Action`1 action) +204
Umbraco.Core.CoreBootManager.Complete(Action`1 afterComplete) +185
Umbraco.Web.WebBootManager.Complete(Action`1 afterComplete) +74
Umbraco.Core.UmbracoApplicationBase.StartApplication(Object sender, EventArgs e) +241
Umbraco.Core.UmbracoApplicationBase.Application_Start(Object sender, EventArgs e) +40
[HttpException (0x80004005): Object reference not set to an instance of an object.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9905705
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): Object reference not set to an instance of an object.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9885060
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
I Added attribute Primary key to the classes as below and everything went well.
[TableName("Projects")]
[PrimaryKey("Id", autoIncrement = true)] // This was missing
public class Project
{
[PrimaryKeyColumn(AutoIncrement=true)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
[TableName("Students")]
[PrimaryKey("Id", autoIncrement = true)] // this was missing
//, but only affected class with foreign key
public class Student
{
[PrimaryKeyColumn(AutoIncrement=true)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[ForeignKey(typeof(Project))]
public int ProjectId { get; set; }
}

EF-Code First: Unable to create a constant value of type ''. Only primitive types ('such as Int32, String, and Guid') are supported in this context

I am currently having trouble with some some linq using EF code first. My current code works fine:
My database model
public class MyDatabase : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Visit> Visits { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
}
public class Visit
{
public int VisitId { get; set; }
public string Name {get; set;}
public int PersonId { get; set; }
public string VisitStatus { get; set; }
public virtual Person People { get; set; }
//There is a one to many relationship to person
}
public class Role
{
public Role()
{
People = new HashSet<Person>();
}
[Key]
public int RoleId { get; set; }
public string Name { get; set; }
public virtual ICollection<Person> People { get; set; }
//There is a many to many relationship to person
}
My query
public IEnumerable<VisitDetails> GetGuestVisiterList()
{
using (var db = new MyDatabase())
{
return (from p in db.People
where p.Roles.Any(a => a.Name == "Guest")
select new GuestVisitDetails
{
PersonId = p.PersonId,
Forename = p.Forename,
Surname = p.Surname,
NumberOfVisits = db.Visits.Count(v => v.PersonId == p.PersonId && v.VisitStatus != "Complete")
}).ToList();
}
}
My View model
public class GuestVisitDetails
{
public int PersonId { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public int NumberOfVisits { get; set; }
}
But when I try to use an interface for my database model so I can unit test, it get the following error:
Unable to create a constant value of type 'MyVisits.Data.Model.Visit'. Only primitive types ('such as Int32, String, and Guid') are supported in this context
My Datebase interface
public class MyDatabase : DbContext, IDolphinDatabase
{
public IDbSet<Person> People { get; set; }
public IDbSet<Role> Roles { get; set; }
public IDbSet<Visit> Visits { get; set; }
}
public interface IMyDatabase : IDisposable
{
public IDbSet<Person> People { get; set; }
public IDbSet<Role> Roles { get; set; }
public IDbSet<Visit> Visits { get; set; }
}
My new Query, I created a dbFactory to just get the IMyDatabase
public IEnumerable<VisitDetails> GetGuestVisiterList(int paperId)
{
using (var db = _dbFactory.GetDatabase())
{
return (from p in db.People
where p.Roles.Any(a => a.Name == "Guest")
select new GuestVisitDetails
{
PersonId = p.PersonId,
Forename = p.Forename,
Surname = p.Surname,
NumberOfVisits = db.Visits.Count(v => v.PersonId == p.PersonId && v.VisitStatus != "Complete")
}).ToList();
}
}
I've found out that it is the 'NumberOfVisits' that is causing the problem but am unsure why or how to fix it.
As requested the stack trace
[NotSupportedException: Unable to create a constant value of type 'MyVisits.Data.Model.Visit'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.]
System.Data.Objects.ELinq.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq) +902
System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54
System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110
System.Data.Objects.ELinq.<>c__DisplayClass77.<TypedTranslate>b__75(Expression e) +11
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +151
System.Data.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator`3.Validate(IEnumerable`1 argument, String argumentName, Int32 expectedElementCount, Boolean allowEmpty, Func`3 map, Func`2 collect, Func`3 deriveName) +237
System.Data.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator`3.Validate() +46
System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.CreateExpressionList(IEnumerable`1 arguments, String argumentName, Boolean allowEmpty, Action`2 validationCallback) +142
System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.ValidateNewCollection(IEnumerable`1 elements, DbExpressionList& validElements) +72
System.Data.Objects.ELinq.NewArrayInitTranslator.TypedTranslate(ExpressionConverter parent, NewArrayExpression linq) +121
System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54
System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110
System.Data.Objects.ELinq.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq) +520
System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54
System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110
System.Data.Objects.ELinq.AggregateTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) +86
System.Data.Objects.ELinq.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) +14
System.Data.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) +102
System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54
System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110
System.Data.Objects.ELinq.MemberInitTranslator.TypedTranslate(ExpressionConverter parent, MemberInitExpression linq) +310
System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54
System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110
System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input) +80
System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding& binding) +88
System.Data.Objects.ELinq.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda) +85
System.Data.Objects.ELinq.SelectTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) +37
System.Data.Objects.ELinq.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) +14
System.Data.Objects.ELinq.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) +102
System.Data.Objects.ELinq.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) +54
System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) +110
System.Data.Objects.ELinq.ExpressionConverter.Convert() +16
System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption) +110
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +149
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +44
System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() +40
System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +40
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +315
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
MyVisits.Business.<GetGuestVisiterList>c__Binding.Invoke(Object& instance, Arguments arguments, Object aspectArgs) in E:\Visual Studio\Projects\MyVisits_current\MyVisits.Business\VisitService.cs:459
PostSharp.Aspects.Internals.MethodInterceptionArgsImpl`1.Proceed() +23
MvcMiniProfiler.Aop.MiniProfilerAttribute.OnInvoke(MethodInterceptionArgs args) in E:\Visual Studio\Projects\MyVisits_current\MvcMiniProfiler.Aop\MiniProfilerAttribute.cs:17
MyVisits.Business.VisitService.GetGuestVisiterList() in :0
MyVisits.Web.Areas.RegionalAdministrator.Controllers.VisitController.EditVisitor() in E:\Visual Studio\Projects\MyVisits_current\MyVisits.Web\Areas\RegionalAdministrator\Controllers\VisitController.cs:85
lambda_method(Closure , ControllerBase , Object[] ) +101
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
Castle.Proxies.ControllerActionInvokerProxy.InvokeActionMethod_callback(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
Castle.Proxies.Invocations.ControllerActionInvoker_InvokeActionMethod.InvokeMethodOnTarget() +154
Castle.DynamicProxy.AbstractInvocation.Proceed() +56
Glimpse.Mvc3.Interceptor.InvokeActionMethodInterceptor.Intercept(IInvocation invocation) +336
Castle.DynamicProxy.AbstractInvocation.Proceed() +94
Castle.Proxies.ControllerActionInvokerProxy.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +214
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8920029
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Any help would be great
First, you should change your entities, to support your relationships:
public class Person
{
public int PersonId { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
// add a collection-reference to roles
public virtual ICollection<Role> Roles { get; set; }
// add a collection-reference to visites
public virtual ICollection<Visit> Visits { get; set; }
}
public class Visit
{
public int VisitId { get; set; }
public string Name {get; set;}
public string VisitStatus { get; set; }
public int PersonId { get; set; }
public virtual Person People { get; set; }
//There is a one to many relationship to person
}
public class Role
{
public Role()
{
People = new HashSet<Person>();
}
[Key]
public int RoleId { get; set; }
public string Name { get; set; }
public virtual ICollection<Person> People { get; set; }
//There is a many to many relationship to person
}
Your problem resolved now. But you can also change the query like this:
public IEnumerable<VisitDetails> GetGuestVisiterList(int paperId)
{
using (var db = _dbFactory.GetDatabase())
{
return (from p in db.People
where p.Roles.Any(a => a.Name == "Guest")
select new GuestVisitDetails
{
PersonId = p.PersonId,
Forename = p.Forename,
Surname = p.Surname,
NumberOfVisits = p.Visits.Count(v => v.VisitStatus != "Complete")
}).ToList();
}
}
Let me know if you have any problem or questions or need clarifications on any part. Cheers.

Categories