AutoMapperMappingException: Missing type map configuration or unsupported mapping. [.NET Core 3.1] - asp.net-web-api

I've build a WebAPI .NET Core 3.1 using AutoMapper v10.0 and AutoMapper Dependency Injection 8.0.1 and I'm encountering the following error
AutoMapperMappingException: Missing type map configuration or unsupported mapping.
Mapping types:
Role -> RoleResources
Entity.Models.Role -> Entity.Resources.RoleResources
lambda_method(Closure , Role , RoleResources , ResolutionContext )
AutoMapperMappingException: Error mapping types.
Mapping types:
ICollection`1 -> ICollection`1
System.Collections.Generic.ICollection`1[[Entity.Models.Role, Entity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.ICollection`1[[Entity.Resources.RoleResources, Entity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
lambda_method(Closure , ICollection<Role> , ICollection<RoleResources> , ResolutionContext )
I've tired to use .ReverseMap(), Mapthe ICollection directly in the profile with no luck.
Here is my classes
Role.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entity.Models
{
[Table("Role")]
public class Role
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int RoleNumber { get; set; }
public ICollection<RolePrivilage> RolePrivilages { get; set; }
}
}
RoleResources.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Entity.Resources
{
public class RoleResources
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int RoleNumber { get; set; }
}
}
Startup.cs Configure method
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<WhiteLandsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
services.AddAutoMapper(typeof(Startup));
services.AddScoped<IRoleService, RoleService>();
services.AddScoped<IPrivilageService, PrivilageService>();
services.AddScoped<IRoleRepository, RoleRepository>();
services.AddScoped<IPrivilageRepository, PrivilageRepository>();
}
Mapping Profile
using AutoMapper;
using Entity.Models;
using Entity.Resources;
using System.Collections.Generic;
namespace Core.Mapping
{
public class MappingProfile : Profile
{
public MappingProfile()
{
//CreateMap<ICollection<Role>, ICollection<RoleResources>>();
CreateMap<Role, RoleResources>();
}
}
}
RoleController.cs
[HttpGet]
public async Task<ICollection<RoleResources>> Get()
{
var roles = await _roleService.List();
var resources = _mapper.Map<ICollection<Role>, ICollection<RoleResources>>(roles);
return resources;
}

can you please register your automapper in configuration service like below and give it a try ?
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

Related

Cant use system.web.security and HttpContext.Current.User.Identity.Name in dot net core 6

I'm trying to migrate from ASP.NET MVC on .NET 4.5 to ASP.NET Core 6,
I can't use System.Web.Security any more.
I also can't use HttpContext.Current.User.Identity.Name. Please suggest an alternative to implement the same functionality:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Ibq.Wages.ManagementSystem.Models;
using Microsoft.AspNetCore.Http;
namespace Ibq.Wages.ManagementSystem.AppStart
{
public class CustomRoleProvider : RoleProvider
{
public int UserCompanyId { get; set; }
public string PayerQid { get; set; }
public string PayerEid { get; set; }
public bool OTPCompleted { get; set; }
public int? AuthorizationLevels { get; set; }
private PIBQWS_prodContext context = new PIBQWS_prodContext();
public override string ApplicationName { get; set; }
public CustomRoleProvider()
{
if(String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name) == false)
UserCompany(HttpContext.Current.User.Identity.Name);
}
}
}

Entity History is not working in aspnetboilerplate

I am using aspnetboilerplate and added below configuration in preintiliaze in module. I have also added data annotation Audited to my entity but still it is not working. My entity is inheriting from AuditedEntity as don't need deleted feature. Please help
Configuration.EntityHistory.IsEnabled = true; Configuration.EntityHistory.Selectors.Add(new NamedTypeSelector("Abp.AuditedEntities", type => typeof(AuditedEntity).IsAssignableFrom(type)));
I have taken reference from here Can't enable Entity History in ASP.NET Zero
Below is entity definition
[Audited]
public partial class QuestionResponse : AuditedEntity<long>
{
public long ApplicationId { get; set; }
public long QuestionId { get; set; }
public string Response { get; set; }
public string Remark { get; set; }
public bool IsActive { get; set; }
public Application Application { get; set; }
public AbpUsers CreatorUser { get; set; }
public AbpUsers LastModifierUser { get; set; }
public Question Question { get; set; }
}
AuditedEntity<long> is not assignable to AuditedEntity.
Add a selector based on the interface IAuditedEntity instead.
Configuration.EntityHistory.Selectors.Add(
new NamedTypeSelector("Abp.AuditedEntities", type =>
// typeof(AuditedEntity).IsAssignableFrom(type)));
typeof(IAuditedEntity).IsAssignableFrom(type)));
Reference
From aspnetboilerplate/aspnetboilerplate's AuditedEntity.cs:
public abstract class AuditedEntity : AuditedEntity<int>, IEntity
{
}
public abstract class AuditedEntity<TPrimaryKey> : CreationAuditedEntity<TPrimaryKey>, IAudited
{
...
}

IQueryable<Patron> does not contain a definition for FirstName and no extension method First Name

I'm starting to learn ASP.NET Core and I stuck in one error and don't understand what is problem.
It says:
IQueryable<Patron> does not contain a definition for FirstName and no extension method FirstName accepting a first argument of type IQueryable<Patron> could be found (are you missing a using directive or an assembly reference?"
So my code so far:
Patron.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace LibaryData.Models
{
public class Patron
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public DateTime DateOfBirth { get; set; }
public string TelephoneNumber { get; set; }
public virtual LibaryCard LibaryCard { get; set; }
public virtual LibaryBranch HomeLibaryBranch { get; set; }
}
}
CheckoutServices.cs
using LibaryData;
using LibaryData.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibaryData.Models;
namespace LibaryServices
{
public class ChekoutService : ICheckout
{
private LibaryContext _context;
public ChekoutService(LibaryContext context)
{
_context = context;
}
public string GetCurrentCheckoutPatron(int assetId)
{
var checkout = GetCheckoutByAssetId(assetId);
if(checkout == null)
{
return "";
}
var cardId = checkout.LibaryCard.Id;
var patron = _context.Patrons
.Include(p => p.LibaryCard)
.Where(p => p.LibaryCard.Id == cardId);
return patron.FirstName + " " + patron.LastName;
}
private Checkout GetCheckoutByAssetId(int assetId)
{
return _context.Checkouts
.Include(co => co.LibaryAsset)
.Include(co => co.LibaryCard)
.Where(co => co.LibaryAsset.Id == assetId)
.FirstOrDefault(co => co.LibaryAsset.Id ==assetId);
}
}
}
So in my class CheckoutServices in method GetCurrentCheckoutPatron I can not call a object patron.FirstName and patron.LastName
As you can see all classes are public, references is already there.
Any suggestion?
Replace .Where with .First to get a Patron and not a IQueryable<Patron>
Edit
Note that if you use .First, an exception can be raised if there's no match.
However, if you use .FirstOrDefault and there's no match, it will return null, so you'll get a NullReferenceException when trying to access patron.FirstName.
Be carefull to check for nulls
In your method GetCurrentCheckoutPatron the variable patron is an IQueryable. If you are expecting only single result from the query, you might want to call FirstOrDefault.

Why can't I use the Column data annotation with Entity Framework 5?

I want to use the Column data annotation as shown in the sample code below but the compiler (and also IntelliSense) do not seem to know that particular data annotation. I'm using EF 5 in Visual Studio 2010. I installed EF 5 using NuGet. The Required and MaxLength annotations are working.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Model
{
public class Destination
{
public int DestinationId { get; set; }
[Required]
public string Name { get; set; }
public string Country { get; set; }
[MaxLength(500)]
public string Description { get; set; }
[Column(TypeName="image")]
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}
}
What am I missing?
Column is in:
using System.ComponentModel.DataAnnotations.Schema;
the following code:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace ConsoleApplication2
{
public class MyContext : DbContext
{
public IDbSet<Entity> Entities { get; set; }
}
public class Entity
{
public int Id { get; set; }
[Column(TypeName = "image")]
public byte[] Photo { get; set; }
}
}
produces:

How to make the entity key value user-assigned

I'm retrieving data from another database that has already created unique IDs for each "beer" entity. However, when I assign the unique key value from the remote database to a new "beer" object, it gets replaced as soon as the object is inserted into the database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using BeerRecommender.Models.ViewModels;
namespace BeerRecommender.Models
{
public class Beer
{
public Beer()
{
Created = DateTime.Now;
Updated = DateTime.Now;
}
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Brewery Brewery { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public ICollection<City> Cities { get; set; }
public ICollection<Tag> Tags { get; set; }
public Style Style { get; set; }
}
}
I'm using the UnitOfWork pattern.
UnitOfWork.BeerRepository.Insert(beer);
UnitOfWork.Save();
As you already discovered, EF will generate values for int primary keys. To fine tune this behavior you need to mark your key with the DatabaseGenerated attribute (or you can also configure this with the the fluent api's HasDatabaseGeneratedOption method):
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }

Resources