map string filed to generic list in automapper based on .net core - asp.net-core

I have a DomainModel and a DTO like this :
public class PostEntity: IEntity
{
[Required]
public string Description { get; set; }
public int Id { get; set; }
[Required]
public string Slug { get; set; }
[Required]
public string Tags { get; set; }
[Required]
public string Title { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public DateTime? UpdatedOn { get; set; }
public PostStatus Status { get; set; }
public User Writer { get; set; }
public int WriterId { get; set; }
}
public class PostDto
{
public int Id { get; set; }
public string Description { get; set; }
public string Slug { get; set; }
public string Tags { get; set; }
public string Title { get; set; }
public DateTime CreatedOn { get; }
public List<string> TagList { get; set; }
public PostDto()
{
TagList = new List<string>();
}
}
PostEntity'Tags contains some tags seperated by ",", now I want to split tags value by "," and convert it to List, to do this, I've tried this but I get the below compilation error
CreateMap<PostEntity, PostDto>().ForMember(dest => dest.TagList, cc => cc.MapFrom(src => src.Tags.Split(",").ToList()));
I get this error :
An expression tree may not contain a call or invocation that uses optional arguments

I can't reproduce your error, it seems to work fine.
Below is an example where the TagList is correctly mapped
The code I used :
MapperConfiguration MapperConfiguration = new MapperConfiguration(configuration =>
{
configuration
.CreateMap<PostEntity, PostDto>().ForMember(dest => dest.TagList, cc => cc.MapFrom(src => src.Tags.Split(',').ToList()));
});
IMapper mapper = MapperConfiguration.CreateMapper();
PostEntity postEntity = new PostEntity
{
Tags = "Tag1,Tag2,Tag3,Tag4"
};
var mappedObject = mapper.Map<PostEntity, PostDto>(postEntity);

Please bear in mind that Expression.Call API does not support optional parameters. So, you should Replace Split(',') with
Split(',', System.StringSplitOptions.None)
or
Split(',', System.StringSplitOptions.RemoveEmptyEntries)
doing so you won't see that error again.

Related

Getting error when adding new object with HTTP POST in .NETCore

I am new to .NetCore and Blazor. I am trying to do a POST of an new Anime, but I am allways getteing the error "The Genre field is required." I have added the genreId to the JSON Object but still the same error -> Screenshot of the error
It's one to many relation, where one animal can have only one genre but one genre can have many enemies.
I don't know if it's useful but here are screenshots of my two tables in the DB -> Anime table and the Genre tab
Here are my to Models:
Anime model
public class Anime
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string CoverImage { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public Genre Genre { get; set; }
public string Studio { get; set; } = string.Empty;
public DateTime? ReleaseDate { get; set; }
public DateTime? EndDate { get; set; }
}
Genre model
public class Genre
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
[JsonIgnore]
public List<Anime> Animes { get; set; }
}
AnimeService where I am adding the new anime to the DB
public async Task<ServiceResponse<List<Anime>>> AddAnime(Anime NewAnime)
{
ServiceResponse<List<Anime>> serviceResponse = new ServiceResponse<List<Anime>>();
_dataContext.Animes.Add(NewAnime);
await _dataContext.SaveChangesAsync();
var animes = await _dataContext.Animes
.Include(a => a.Genre)
.ToListAsync();
if (animes == null)
{
serviceResponse.Success = false;
serviceResponse.Message = "Animes could be found!";
}
serviceResponse.Data = animes;
return serviceResponse;
}
AnimeController
[HttpPost]
[Route("AddAnime")]
public async Task<ActionResult<ServiceResponse<List<Anime>>>> AddAnime(Anime NewAnime)
{
return Ok(await _animeService.AddAnime(NewAnime));
}
As we discussed on Discord:
You're using .NET 6 with nullables enabled.
As an Anime can exist before it has Genre assigned I would configure the tables like this:
public class Anime
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string CoverImage { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public int? GenreId { get; set; }
[ForeignKey(nameof(GenreId))]
public Genre? Genre { get; set; }
public string Studio { get; set; } = string.Empty;
public DateTime? ReleaseDate { get; set; }
public DateTime? EndDate { get; set; }
}
public class Genre
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
[JsonIgnore]
[InverseProperty(nameof(Anime.Genre))]
public List<Anime> Animes { get; set; }
}
It seems that your Anime instance don't habe a Genre object but it is requiered in your db context
You have to add navigation property GenreId as nullable if you think that Genre is optional
public class Anime
{
public int Id { get; set; }
... another properties
public int? GenreId { get; set; }
public virtual Genre Genre { get; set; }
}
after this you will have to make a new database migration

ASP.Net core - make a search inside a nested collection

I'm trying to make a nested collection search and I'm really struggling.
My expected result is: I would like to make a search and find all the powerUp objects by a certain date. (PowerUpDate property - that's the searching criteria)
User Model:
public class AppUser : IdentityUser
{
public ICollection<Hero> Heroes { get; set; }
}
Hero Model:
[Table("Heroes")]
public class Hero
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Ability { get; set; }
[Required]
public string SuitColors { get; set; }
public double CurrentPower { get; set; }
public double StartingPower { get; set; }
public DateTime Created { get; set; } = DateTime.Now;
public ICollection<PowerUp> PowerUps { get; set; }
public AppUser AppUser { get; set; }
[Required]
public string AppUserId { get; set; }
}
PowerUp Model:
[Table("PowerUps")]
public class PowerUp
{
public int Id { get; set; }
[Required]
public double PowerUpIncrement { get; set; }
[Required]
public DateTime PowerUpDate { get; set; } = DateTime.Now;
public Hero Hero { get; set; }
[Required]
public int HeroId { get; set; }
}
DataContext:
public class DataContext : IdentityDbContext<AppUser>
{
public DataContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Hero>().HasMany(hero => hero.PowerUps).WithOne(powerUp => powerUp.Hero)
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<AppUser>().HasMany(user => user.Heroes).WithOne(hero => hero.AppUser)
.OnDelete(DeleteBehavior.Cascade);
}
}
Could someone please explain to me how can I implement such a search on a nested collection?
Inject your AppUser user using Dependency injection
(better use the repository pattern) anyway it should be something like this: user.Heroes.PowerUps.OrderBy(x=>x.PowerUpDate == Datetime.Now).ToList();
x.PowerUpDate == To whatever date you will insert

Problem with mapping two objects (with lists)

I am looking for solution my issue... Probably my Shifts class cannot be mapped.
I have entity class Worker:
public class Worker
{
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
[MaxLength(50)]
public string LastName { get; set; }
[MaxLength(200)]
public string PhotoFilePath { get; set; }
public Workplace Workplace { get; set; }
public int WorkplaceId { get; set; }
public List<Service> Services { get; set; }
public List<Shift> Shifts { get; set; }
public IEnumerable<Worker> ToList()
{
throw new NotImplementedException();
}
}
And model WorkerModel:
public int Id { get; set; }
[Required]
[DisplayName("Imię")]
public string Name { get; set; }
[DisplayName("Nazwisko")]
public string LastName { get; set; }
[Display(Name = "Zdjęcie")]
public IFormFile Photo { get; set; }
public string PhotoFilePath { get; set; }
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int WorkplaceId { get; set; }
public List<ServiceModel> Services { get; set; }
public List<ShiftModel> Shifts { get; set; }
}
My default mapper profile:
//Mapping workers
CreateMap<Worker, WorkerModel>();
CreateMap<WorkerModel, Worker>();
And when I try map model to entity class in my action:
Worker worker = _mapper.Map<Worker>(model);
I get an issue:
AutoMapperMappingException: Missing type map configuration or unsupported mapping.
This is caused by different mapping types. Take the property Service as an example.
The resource is a type of Service.
But the destination is a type of ServiceModel.
So, they need to be converted. Here is a demo.
I create the Service and ServiceModel according to your model.
public class Service
{
public int serviceID { get; set; }
public string myservice { get; set; }
}
public class ServiceModel
{
public int serviceID { get; set; }
public string myservice { get; set; }
}
This is mapping relationship.
public class AutomapProfile : Profile
{
public AutomapProfile()
{
CreateMap<Worker, WorkerModel>();
CreateMap<WorkerModel, Worker>()
.ForMember(m => m.Services, x => x.MapFrom(y => y.Services.Select(a=>
new Service
{
serviceID=a.serviceID,
myservice=a.myservice
})));
}
}
This is the mapping method.
public IActionResult Index()
{
var model = new WorkerModel
{
Id=1,
Name="names",
//...
Services = new List<ServiceModel>
{
new ServiceModel{ serviceID=1, myservice="service1"},
new ServiceModel{ serviceID=2, myservice="service2"},
},
//...
};
Worker worker = _mapper.Map<Worker>(model);
return Ok(worker);
}
Result.

Automapper ConstructUsing not working as expected

I am using automapper in my asp.net core project and it's my first time with that library. The data flow is as follows: Model->DomainModel->ViewModel. Automapper is used for mapping between those. I have problems using ConstructUsing. It seems to me it is not working.
Part of the data profile class:
CreateMap<ClinicD, ClinicViewModel>()
.ConstructUsing(x => new ClinicViewModel
{
Active = x.Active,
CooperationStart = x.CooperationStart,
CooperationEnd = x.CooperationEnd,
Id = x.Id,
Name = x.Name,
AddressId = x.Address.Id,
FlatNo = x.Address.FlatNo,
City = x.Address.City,
HouseNumber = x.Address.HouseNumber,
Street = x.Address.Street,
Postcode = x.Address.Postcode
})
.ForMember(x => x.ChosenSpecialities, opt => opt.Ignore())
.ForMember(x => x.Specialities, opt => opt.Ignore());
public class ClinicViewModel : CooperationSpotViewModel
{
private IEnumerable<int> _chosenSpecialities;
public IEnumerable<SelectListItem> Specialities
{
get;set;
}
public IEnumerable<int> ChosenSpecialities
{
get
{
if (_chosenSpecialities == null)
_chosenSpecialities = new List<int>();
return _chosenSpecialities;
}
set
{
if (value != null)
_chosenSpecialities = value;
}
}
}
public abstract class CooperationSpotViewModel : BaseViewModel
{
public int? Id { get; set; }
public string Name { get; set; }
public DateTime? CooperationStart { get; set; }
public DateTime? CooperationEnd { get; set; }
public bool? Active { get; set; }
public string PhoneNumber { get; set; }
public int? AddressId { get; set; }
public string Street { get; set; }
public string HouseNumber { get; set; }
public string FlatNo { get; set; }
public string City { get; set; }
public string Postcode { get; set; }
}
public class ClinicD : CooperationSpotD
{
public IEnumerable<SpecialityD> Specialities
{
get;set;
}
}
public abstract class CooperationSpotD
{
public int? Id { get; set; }
public string Name { get; set; }
public DateTime? CooperationStart { get; set; }
public DateTime? CooperationEnd { get; set; }
public bool? Active { get; set; }
public string PhoneNumber { get; set; }
public AddressD Address { get; set; }
}
A similar issue occurs for me in several spots, so I am guessing, I must be doing something basic wrong. The exception that occurs:
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
ClinicD -> ClinicViewModel (Destination member list)
SeeingEyeDog.BusinessLogic.Models.ClinicD -> SeeingEyeDog.Models.ClinicViewModel (Destination member list)
Unmapped properties:
Street
HouseNumber
FlatNo
City
Postcode

Entity Framework Parent\Child Retrieval

I have an ID of a "Component" parent record that I need to retrieve all the "Attachment" child records. The grid I am using need fields returned an placed in "TheComponentAttachmentsJoinedTable" I am only able to retrieve one record. I have used the value of FirstorDefault. That is the only way it will accept the line of code without complaining about the IEnumerable to int. Could someone please explain what is incorrect?
public class Component
{
public int ID { get; set; }
public string ComponentCode { get; set; }
public string ComponentDescription { get; set; }
public double ComponentWeight { get; set; }
public double ComponentQuantity { get; set; }
public string LastModUser { get; set; }
public DateTime LastModDate { get; set; }
public virtual ICollection<Attachment> Attachments { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Element> Elements { get; set; }
}
public class Attachment
{
public int ID { get; set; }
public string AttachmentDescription { get; set; }
public string OriginalName { get; set; }
public string MimeType { get; set; }
public byte[] bytes { get; set; }
public string LastModUser { get; set; }
public DateTime LastModDate { get; set; }
//Navigation
public virtual ICollection<Element> Elements { get; set; }
public virtual ICollection<Component> Components { get; set; } //lt M-m
}
public class TheComponentAttachmentsJoinedTable
{
public int ComponentID { get; set; }
public int AttachmentID { get; set; }
public string OriginalName { get; set; }
}
public static List<TheComponentAttachmentsJoinedTable> ComponentAttachments_GetAllByComponentID(int ComponentID)
{
using (TheContext TheDB = new TheContext())
{
var r = (from x in TheDB.Component
.Where(x => x.ID == ComponentID)
.Include(x => x.Attachments)
select new TheComponentAttachmentsJoinedTable
{
ComponentID = x.ID,
AttachmentID = x.Attachments.Select(y => (y.ID)).FirstOrDefault(),
OriginalName = x.Attachments.Select(y => y.OriginalName).FirstOrDefault().ToString(),
}
);
return r.ToList();
}