Can't convert from model to viewmodel, using AutoMapper asp.net core - asp.net

I am using Auto mapper to map between modelviews and models. I have followed the same steps given by the Auto mapper documentation and still can't find where the issue is.
public class RegisterStaffViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "StaffName Required")]
public string StaffName { get; set; }
[Required(ErrorMessage = "Gender Required")]
public string Gender { get; set; }
[Required(ErrorMessage = "Address Required")]
public string Address { get; set; }
[Required(ErrorMessage = "StaffCode Required")]
public string StaffCode { get; set; }
[DisplayName("Department")]
[Required(ErrorMessage = "Department is Required")]
public int? DepartmentId { get; set; }
public string CardNo { get; set; }
[Required(ErrorMessage = "Mobileno Required")]
[RegularExpression(#"^(\d{10})$", ErrorMessage = "Wrong Mobileno")]
public string MobileNo { get; set; }
[Required(ErrorMessage = "EmailID Required")]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]
public string Email { get; set; }
public DateTime EntryDate { get; set; }
[Display(Name = "Position")]
[Required(ErrorMessage = "Position is Required")]
public int? PositionId { get; set; }
[Display(Name = "Staff Type")]
[Required(ErrorMessage = "Staff Type is Required")]
public int? StaffTypeId { get; set; }
public string CardIdNo { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsUpdated { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public string DeletedBy { get; set; }
public string Remarks { get; set; }
public virtual ApplicationUser CreatedByNavigation { get; set; }
public virtual ApplicationUser DeletedByNavigation { get; set; }
public virtual Departments Department { get; set; }
public virtual Positions Position { get; set; }
public virtual StaffTypes StaffType { get; set; }
public virtual ApplicationUser UpdatedByNavigation { get; set; }
public virtual ICollection<AttendanceRecorderViewModel> AttendanceRecorder { get; set; }
public virtual ICollection<ManageLeavesViewModel> ManageLeaves { get; set; }
public virtual ICollection<RegisterDevicesViewModel> RegisterDevices { get; set; }
}
=============================================================================================
public partial class RegisterStaffs
{
public int Id { get; set; }
public string StaffName { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string StaffCode { get; set; }
public int? DepartmentId { get; set; }
public string CardNo { get; set; }
public string MobileNo { get; set; }
public string Email { get; set; }
public DateTime EntryDate { get; set; }
public int? PositionId { get; set; }
public int? StaffTypeId { get; set; }
public string CardIdNo { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsUpdated { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public string DeletedBy { get; set; }
public string Remarks { get; set; }
public virtual ApplicationUser CreatedByNavigation { get; set; }
public virtual ApplicationUser DeletedByNavigation { get; set; }
public virtual Departments Department { get; set; }
public virtual Positions Position { get; set; }
public virtual StaffTypes StaffType { get; set; }
public virtual ApplicationUser UpdatedByNavigation { get; set; }
public virtual ICollection<AttendanceRecorder> AttendanceRecorder { get; set; }
public virtual ICollection<ManageLeaves> ManageLeaves { get; set; }
public virtual ICollection<RegisterDevices> RegisterDevices { get; set; }
}
============================================================================================
public interface IMapperConfig
{
IMapper CreateMapper();
}
public class MapperConfig : IMapperConfig
{
public IMapper CreateMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RegisterStaffs, RegisterStaffViewModel>();
cfg.CreateMap<AttendanceRecorder, AttendanceRecorderViewModel>();
cfg.CreateMap<ManageLeaves, ManageLeavesViewModel>();
cfg.CreateMap<RegisterDevices, RegisterDevicesViewModel>();
});
return config.CreateMapper();
}
}
==========================================================================================
public async Task<ReturnResult<List<RegisterStaffViewModel>>> GetAllEmployees()
{
var result = new ReturnResult<List<RegisterStaff>>();
try
{
var employees = await context.RegisterStaffs.Where(x => (bool)!x.IsDeleted).OrderByDescending(x => x.EntryDate).AsNoTracking().ToListAsync();
// **here is the error**
result.Success(mapper.Map<List<RegisterStaffs>, List<RegisterStaffViewModel>>(employees));
}
catch(Exception ex)
{
}
return result;
}
============================================================================================
public class ReturnResult<T>
{
public ReturnResult()
{
ErrorList = new List<string>();
}
public bool IsSuccess { get; set; }
public HttpCode HttpCode { get; set; }
public T Data { get; set; }
public List<string> ErrorList { get; set; }
/// <summary>
/// Set success result with data
/// </summary>
/// <param name="Data"></param>
public void Success(T Data)
{
this.IsSuccess = true;
this.HttpCode = HttpCode.Success;
this.Data = Data;
}
/// <summary>
/// Set Server Error result with error message
/// </summary>
/// <param name="Error"></param>
public void ServerError(string Error)
{
this.IsSuccess = false;
this.HttpCode = HttpCode.ServerError;
this.ErrorList.Add(Error);
}
/// <summary>
/// Set Not Found result with error message
/// </summary>
/// <param name="Error"></param>
public void NotFound(string Error)
{
this.IsSuccess = false;
this.HttpCode = HttpCode.NotFound;
this.ErrorList.Add(Error);
}
}

I found the issue was here
var result = new ReturnResult<List<RegisterStaff>>();
i have changed it to
var result = new ReturnResult<List<RegisterStaffViewModel>>();

Related

Deserialize json without root object and 1 array ASP.NET MVC

I'm building a web application that's using a third parties API and I receive the json below
{
"CompanyID": 14585,
"CompanyName": "The Morgan Group Daytona, LLC",
"BillingAddressLine": "100 S Beach St #200",
"BillingAddressCity": "Daytona Beach",
"BillingAddressState": "Fl",
"BillingAddressPostCode": "32114",
"BillingCountryCode": "US",
"BillingAddress": "100 S Beach St #200\r\nDaytona Beach Fl 32114\r\nUNITED STATES",
"Phone": null,
"Fax": null,
"website": null,
"TaxNumber": null,
"Comments": null,
"CurrencyCode": "USD",
"DefaultTradingTermIDFK": 15,
"DateCreated": "2020-09-04T18:25:02",
"DateUpdated": "2020-09-04T18:25:02",
"Contacts": [
{
"ContactID": 13781,
"CompanyIDFK": 14585,
"CompanyName": null,
"Firstname": "Test",
"Lastname": "User",
"Email": "test#test.com",
"Phone": null,
"Mobile": "4075551234",
"PositionTitle": "Test Title",
"TimeZone": "Eastern Standard Time",
"DateCreated": "2020-09-07T02:21:10",
"DateUpdated": "2020-09-07T02:21:10"
}
]
}
All of the other json responses for the other API calls also do not have root objects. The goal is to use razor to display this information on the view. Whats the most efficient way to do so?
So far I've created this class file
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
but now i'm stuck on trying to figure out how to deserialize something like this? Whats the easiest way to do this. I can't seem to find any other post that matches this same set of circumstances.
When you get a blob of JSON, you can speed things up by going to https://json2csharp.com/ and have it convert it in to classes. For example, that blob returns this:
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string website { get; set; }
public string TaxNumber { get; set; }
public string Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
The classes it returns will sometimes have some small issues, for example, since your blob had a lot of null properties, it just converted them to object. I changed them to string.
Then you simply use Newtonsoft.Json to convert it:
using(var s = File.OpenRead(#"c:\users\andy\desktop\test.json"))
using(var sr = new StreamReader(s))
using(var jtr = new JsonTextReader(sr))
{
var obj = new JsonSerializer().Deserialize<Root>(jtr);
}
And you are finished:
ETA
You posted your code on getting this data and noticed you are using WebRequest. Just a heads up that WebRequest is legacy and you should be using HttpClient. This is how you download/deserialize with HttpClient:
private static readonly HttpClient _httpClient = new HttpClient();
private static async Task<Root> GetStuffFromThereAsync(string token)
{
using(var req = new HttpRequestMessage(HttpMethod.Get,
new Uri("https://www.example.com")))
{
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var resp = await _httpClient.SendAsync(req))
{
resp.EnsureSuccessStatusCode();
using (var s = await resp.Content.ReadAsStreamAsync())
using (var sr = new StreamReader(s))
using (var jtr = new JsonTextReader(sr))
{
return new JsonSerializer().Deserialize<Root>(jtr);
}
}
}
}
If it is still returning null, then there is a chance your models don't match.
You need to use the below the line with class I have mentioned :
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>("This is the your JSON string");
Class
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}

Automapper missing type map configuration or unsupported mapping error

I am using Auto mapper and I am getting this error, I am getting this error within AddAsync() method. Please help me out to solve this issue.
Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\nDepartmentsViewModel -> Departments\r\nEmployeeAttendanceApp.ViewModels.DepartmentsViewModel -> EmployeeAttendanceApp.Models.StaffManagement.Departments
My class
public interface IMapperConfig
{
IMapper CreateMapper();
}
public class MapperConfig : IMapperConfig
{
public IMapper CreateMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RegisterStaffs, RegisterStaffViewModel>();
cfg.CreateMap<AttendanceRecorder, AttendanceRecorderViewModel>();
cfg.CreateMap<ManageLeaves, ManageLeavesViewModel>();
cfg.CreateMap<RegisterDevices, RegisterDevicesViewModel>();
cfg.CreateMap<Departments, DepartmentsViewModel>();
});
return config.CreateMapper();
}
}
public class DepartmentsViewModel
{
[Key]
public int DepartmentId { get; set; }
[DisplayName("اسم القسم/ الادارة")]
[Required(ErrorMessage = "الرجاء ادخال اسم القسم")]
public string DepartmentName { get; set; }
[DisplayName("اضافة ملاحظات القسم")]
public string Remarks { get; set; }
public bool? IsUpdated { get; set; }
public bool? IsDeleted { get; set; }
public string CreatedBy { get; set; }
public string DeletedBy { get; set; }
public string UpdatedBy { get; set; }
[DisplayName("عدد الموظفيين")]
[Required(ErrorMessage = " الرحاء إدخال عدد موظفيين القسم")]
public long? StaffNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public virtual ICollection<RegisterDevicesViewModel> RegisterDevices { get; set; }
public virtual ICollection<RegisterStaffViewModel> RegisterStaffs { get; set; }
}
public partial class Departments
{
[Key]
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string Remarks { get; set; }
public bool? IsUpdated { get; set; }
public bool? IsDeleted { get; set; }
public string CreatedBy { get; set; }
public string DeletedBy { get; set; }
public string UpdatedBy { get; set; }
public long? StaffNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public virtual ICollection<RegisterDevices> RegisterDevices { get; set; }
public virtual ICollection<RegisterStaffs> RegisterStaffs { get; set; }
}
**I am getting the error in this method**
public async Task<bool> AddAsync(DepartmentsViewModel departmentsView)
{
try
{
var department = mapper.Map<DepartmentsViewModel, Departments>(departmentsView);
await context.Departments.AddAsync(department);
await context.SaveChangesAsync();
return true;
}
catch(Exception ex)
{
logger.LogError(ex, ex.Message);
return false;
}
}
//here is startup file where I have registered the services
services.AddSingleton<IMapperConfig, MapperConfig>();
services.AddTransient<IDepartmentManager, DepartmentManager>();
I have resolved this issue by adding .ReverseMap() inside MapperConfig class
cfg.CreateMap<Departments, DepartmentsViewModel>().ReverseMap();
but still I can't understand why it didn't work previously with out it because I have seen various examples never using ReverseMap()

automapping 1:1 mvc unmapped members found

I am trying to use automapper to map between my entites db class and my view model. They have the same exact prop names but i get the error thrown saying unmapped members found. From what I understand if you have 1:1 Relationship you do not have to do the manual mapping in the config file. what am I missing here?
product class
public class product
{
public int id { get; set; }
public string sku { get; set; }
public string ISBN { get; set; }
public string itemName { get; set; }
public int numberCds { get; set; }
public string description { get; set; }
public string category { get; set; }
public double price { get; set; }
public double weight { get; set; }
public int stock { get; set; }
public int stockAlert { get; set; }
public string salesTax { get; set; }
public string imgURL { get; set; }
public string videoURL { get; set; }
public int views { get; set; }
public string instantDownload { get; set; }
public string downloadLink { get; set; }
public int active { get; set; }
public string addedBy { get; set; }
public DateTime addedTime { get; set; }
public string updatedBy { get; set; }
public DateTime updatedTime { get; set; }
}
entites class
public partial class newProduct
{
public int id { get; set; }
public string sku { get; set; }
public string ISBN { get; set; }
public string itemName { get; set; }
public Nullable<int> numberCds { get; set; }
public string description { get; set; }
public string category { get; set; }
public double price { get; set; }
public Nullable<double> weight { get; set; }
public Nullable<int> stock { get; set; }
public Nullable<int> stockAlert { get; set; }
public string salesTax { get; set; }
public string imgURL { get; set; }
public string videoURL { get; set; }
public Nullable<int> views { get; set; }
public string instantDownload { get; set; }
public string downloadLink { get; set; }
public int active { get; set; }
public string addedBy { get; set; }
public Nullable<System.DateTime> addedTime { get; set; }
public string updatedBy { get; set; }
public Nullable<System.DateTime> updatedTime { get; set; }
}
Mapping Config
public static void RegisterMaps()
{
AutoMapper.Mapper.Initialize(config =>
{
config.CreateMap<product, newProduct>();
config.CreateMap<newProduct, product>();
});
}
and the controller
public ActionResult Index()
{
using (StoreEntities db = new StoreEntities())
{
var results = (from p in db.newProducts select p).Where(a => a.active == 1);
var products = AutoMapper.Mapper.Map<product>(results);
return View(products);
}

Cannot save entity one to one EF mvc 5

I am trying to insert a new record into database, no errors, a new record is not created in Applicant and ApplicantNotification table. Not sure what I am doing wrong?
Applicant
[Index]
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ApplicantID { get; set; }
[Required]
public string ApplicantTitle { get; set; }
[Required]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
[Required]
public string Address { get; set; }
[Required]
public string Address1 { get; set; }
[Required]
public string Address2 { get; set; }
[Required]
public string Address3 { get; set; }
[Required]
public string Postcode { get; set; }
[Required]
public string CaseReference { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
/*Spouse*/
public string SpouseTitle { get; set; }
public string SpouseFirstname { get; set; }
public string SpouseLastname { get; set; }
public string SpouseAddress { get; set; }
public string SpouseAddress1 { get; set; }
public string SpouseAddress2 { get; set; }
public string SpouseAddress3 { get; set; }
public string SpousePostcode { get; set; }
ApplicantNotification
[Index]
[Key, Column("ApplicantID"), ForeignKey("Applicant")]
public int ApplicantNotificationID { get; set; }
public bool FirstNotification { get; set; }
public bool SecondtNotification { get; set; }
public bool ThirdNotification { get; set; }
public bool FinalNotification { get; set; }
public DateTime ReminderDate { get; set; }
public int ReminderFrequency { get; set; }
[DataType(DataType.Date)]
public DateTime? FirstNotificationDate { get; set; }
[DataType(DataType.Date)]
public DateTime? SecondNotificationDate { get; set; }
[DataType(DataType.Date)]
public DateTime? ThirdNotificationDate { get; set; }
public bool IsArchive { get; set; }
public virtual Applicant Applicant { get; set; }
ViewModel
public int ApplicantID { get; set; }
[Required]
public string ApplicantTitle { get; set; }
public string ApplicantFirstname { get; set; }
public string ApplicantLastname { get; set; }
public string ApplicantAddress { get; set; }
public string ApplicantAddress1 { get; set; }
public string ApplicantAddress2 { get; set; }
public string ApplicantAddress3 { get; set; }
public string ApplicantPostcode { get; set; }
[Required]
public string ApplicantCaseReference { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ApplicantDateOfBirth { get; set; }
/*Spouse*/
public string SpouseTitle { get; set; }
public string SpouseFirstname { get; set; }
public string SpouseLastname { get; set; }
public string SpouseAddress { get; set; }
public string SpouseAddress1 { get; set; }
public string SpouseAddress2 { get; set; }
public string SpouseAddress3 { get; set; }
public string SpousePostcode { get; set; }
/*Notification*/
public int ApplicantNotificationID { get; set; }
public bool FirstNotification { get; set; }
public bool SecondNotification { get; set; }
public bool ThirdNotification { get; set; }
public bool FinalNotification { get; set; }
public DateTime? ReminderDate { get; set; }
Create Method:
// POST: Applicant/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ApplicantNotificationViewModel model)
{
var applicant = new Applicant();
var applicantNotification = new ApplicantNotification();
if (ModelState.IsValid)
{
SetApplicant(model, applicant);
SetApplicantNotification(model, applicantNotification);
using (var context = new WorkSmartContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
db.Applicants.Add(applicant);
context.SaveChanges();
db.ApplicantNotifcations.Add(applicantNotification);
context.SaveChanges();
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
return RedirectToAction("Index");
}
}
return View(model);
}
Thanks for the suggestions in the comments.
It appears, if the datetime column is set to allow null, then the datetime either has to be set to null or set to the correct format in order for sql datetime to work. Otherwise it throws the
"The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\The statement has been terminated."
https://stackoverflow.com/questions/4608734/the-conversion-of-a-datetime2-data-type-to-a-datetime-data-type-resulted-in-an-o
I set the dates to null in my Entity objects, and entered a new entry to the database.

Retrieving twitter with json

I'm having trouble with parsing a twitter flow, this code is returning this error message:
No parameterless constructor defined for type of
'System.Collections.Generic.IEnumerable`1[[Xxxx.Website.Templates.WidgetViews.Tweet,
Dolphin, Version=1.0.4801.24288, Culture=neutral,
PublicKeyToken=null]]'.
I would very much appreciate your help!
public partial class TwitterWidgetView
{
protected override void OnLoad(System.EventArgs e)
{
string listName = "sas";
string twitterListPath = "https://search.twitter.com/search.json?q=" + listName;
WebClient wc = new WebClient();
var json = wc.DownloadString(twitterListPath);
JavaScriptSerializer ser = new JavaScriptSerializer();
var tweetList = ser.Deserialize<IEnumerable<Tweet>>(json);
}
}
public class Metadata
{
public string result_type { get; set; }
}
public class Tweet
{
public Tweet()
{}
public string created_at { get; set; }
public string from_user { get; set; }
public int from_user_id { get; set; }
public string from_user_id_str { get; set; }
public string from_user_name { get; set; }
public object geo { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string iso_language_code { get; set; }
public Metadata metadata { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string source { get; set; }
public string text { get; set; }
public string to_user { get; set; }
public int to_user_id { get; set; }
public string to_user_id_str { get; set; }
public string to_user_name { get; set; }
public long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
}
public class RootObject
{
public RootObject()
{}
public double completed_in { get; set; }
public long max_id { get; set; }
public string max_id_str { get; set; }
public string next_page { get; set; }
public int page { get; set; }
public string query { get; set; }
public string refresh_url { get; set; }
public List<Tweet> results { get; set; }
public int results_per_page { get; set; }
public int since_id { get; set; }
public string since_id_str { get; set; }
}
Try using a list instead
var tweetList = ser.Deserialize<List<Tweet>>(json);

Resources