AutoMapper issue when try to map Model to ViewModel - dictionary

I'm trying to map with AutoMapper
I have this model from data:
public partial class ModelFromData
{
public int Id { get; set; }
public int LastPosition { get; set; }
public virtual SomeModel SomeModel{ get; set; }
}
And my view Model
public class ViewModel
{
public int Id { get; set; }
public int LastPosition { get; set; }
public virtual SomeModel SomeModel{ get; set; }
}
My Mapper configures:
public class MapperConfig
{
public static void InitMaps()
{
Mapper.CreateMap<ModelFromData, ViewModel>();
Mapper.CreateMap<ViewModel, ModelFromData>();
Mapper.AssertConfigurationIsValid();
}
}
public static class MapExtensions
{
public static T To<T>(this Object from)
{
return Mapper.Map<T>(from);
}
}
When I try to AutoMap I get the folowing error:
Missing type map configuration or unsupported mapping.
Mapping types:
ModelFromData -> ViewModel
enter code here
Project.Data.ModelFromData -> Project.Web.Models.ViewModel

This is the error you will get when trying to map an object before the "CreateMap" is called. What framework are you using? I would hazard a guess at Asp.Net?
If so, Call your MapperConfig.InitMaps(); method from global.asax. Good answer here: https://stackoverflow.com/a/6825394/692830

Related

Creating navigation code-first results in the error: does not declare a navigation property with the name

query.Include("Store_Location").Load();
throws:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: A specified Include path is not valid. The EntityType 'Model.Order' does not declare a navigation property with the name 'Store_Location'.
I used the following code in order to create the navigation code-first:
public partial class Order
{
public Nullable<int> Store_Location_ID { get; set; }
public virtual Store_Location Store_Location { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
public partial class Store_Location
{
public int ID { get; set; }
public virtual ICollection<Order> Orders { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
https://learn.microsoft.com/en-us/ef/ef6/fundamentals/relationships
Do I need to use the designer? Is there anything I need to do in order for the navigation to be created?
If you create your database with code first approach, then your entities should not be partial classes. Define them like this:
public class Order
{
public int? StoreLocationId { get; set; }
public virtual StoreLocation StoreLocation { get; set; }
}
public class StoreLocation
{
public int Id { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
Then you should create a DbContext class:
public class StoreDbContext : DbContext
{
public StoreDbContext(DbContextOptions<StoreDbContext> options) : base(options)
{
}
public virtual DbSet<StoreLocation> StoreLocations { get; set; }
public virtual DbSet<Order> Orders { get; set; }
}
After creating a context you can use the ef commands to create your database. You can read more about ef core here: https://learn.microsoft.com/en-us/ef/core/get-started/?tabs=netcore-cli
If you define your classes like I did above, you can include your navigation properties strongly typed like this:
query.Include(order => order.StoreLocation);

JsonConvert.DeserializeObject<> is returning null last childtoken of the two childrentokens

I am sending a JObject from the frontend to my API, which is divided into First and Last childtokens, as seen in the picture below:
However, when I am trying to use the following code, the last part of childrendtoken is becoming null
var RVoucher = JsonConvert.DeserializeObject<VMReceive>(request.ToString());
This is what I am having in the debugging mode:
Here, the VMReceive is a viewModel that consists of another viewmodel "VMMonth"and an ado.net generated model class "ReceiveVoucher".
Code of the models are given below:
public class VMReceive
{
public List<VMMonth> Month { get; set; }
public ReceiveVoucher receiveVoucher { get; set; }
}
public class VMMonth
{
public int item_id { get; set; }
public string item_text { get; set; }
}
public partial class ReceiveVoucher
{
public int ReceiveVoucherId { get; set; }
public Nullable<int> MonthId { get; set; }
public string ReceivedBy { get; set; }
public string Remarks { get; set; }
public Nullable<int> ReceivedAmount { get; set; }
}
I have also tried putting [JsonProperty("")] over each property of my "ReceiveVoucher" model class, but got the same 'null' issue.
I am not sure about what I am doing wrong here, your suggestion regarding this will be very helpful.
Your JSON property name doesn't match. Your class uses receiveVoucher whereas the JSON is ReceiveAmount. Also, why are you using JObject in the first place, this should work by just using the class name as the action parameter:
public HttpResponse PostReceive([FromBody] VMReceive RVoucher, int userId)
{
...
}

How to fix ‘Cannot create a DbSet for 'DM_NCC_ThueSuat' because this type is not included in the model for the context’ error in C# ASP.NET

I have a code block regards get a list like that in aspnetzero:
public async Task<List<DMNCCThueSuatDto>> GetDSThueSuat()
{
using (_unitOfWorkManager.Current.SetTenantId(null))
{
var lstthueSuat = await _dmThueSuatRepository.Query(t => t.Where(i =>
i.IsDeleted == false)).OrderBy("thuesuat_ma asc").ToListAsync();
return ObjectMapper.Map<List<DMNCCThueSuatDto>>(lstthueSuat);
}
}
I expected a list of DMNCCThueSuatDto is returned but the error
Cannot create a DbSet for 'DM_NCC_ThueSuat' because this type is not
included in the model for the context.
is always displayed.
Also, i had myown a declaration
public virtual DbSet DS_ThueSuat { get; set; }
in my DBContext.
In my mariadb database, i had a table called "vs_dm_ncc_thuesuat"
and i have already declare a class for mapping to the table above
namespace VS.vHoaDon.Domains.DanhMuc.DMNhaCungCap
{
[Table("vs_dm_ncc_thuesuat")]
[MultiTenancySide(MultiTenancySides.Host)]
public class DM_NCC_ThueSuat : FullAuditedEntity
{
public int ThueSuat_Ma { get; set; }
public string ThueSuat_Ten { get; set; }
public int ThueSuat_GiaTri { get; set; }
public bool ThueSuat_HieuLuc { get; set; }
public DateTime? ThueSuat_BatDau { get; set; }
public DateTime? ThueSuat_KetThuc { get; set; }
}
}
I don't know why?
Any helps is appreciated.
Thank you so much.

ASP.NET MVC 4 - Create a ViewModel from a base class (Model)

There is a class (Model) User.cs:
namespace BookStore
{
using System;
using System.Collections.Generic;
public class User
{
public int user_id { get; set; }
public string user_login_name { get; set; }
public string user_first_name { get; set; }
public string user_last_name { get; set; }
}
}
I want to create a ViewModel to then use it in Views. How should I do it? I create ViewModels folder in the project, create a class UserViewModel.cs in it, then what? I just copy and paste the original User.cs content and put limitations? Like this:
namespace BookStore.Models
{
public class UserViewModel
{
[Editable(false)]
public int user_id { get; private set; }
public string user_login_name { get; set; }
public string user_first_name { get; set; }
public string user_last_name { get; set; }
}
}
I did so and now my UserController says it can't implicitly convert type BookStore.User to BookStore.UserViewModel:
public class UserController : Controller
{
private DBEntities db = new DBEntities();
public ActionResult UserDetails()
{
UserViewModel user = db.Users.FirstOrDefault(u => u.user_login_name==User.Identity.Name);
if (user == null)
return RedirectToAction("Create");
else
return View(user);
}
I know it is important in MVC to separate concerns, domain models and view models should be used for different purposes, but why is there no any detailed info on how to create ViewModels correctly?

Using ComplexType with ToList causes InvalidOperationException

I have this model
namespace ProjectTimer.Models
{
public class TimerContext : DbContext
{
public TimerContext()
: base("DefaultConnection")
{
}
public DbSet<Project> Projects { get; set; }
public DbSet<ProjectTimeSpan> TimeSpans { get; set; }
}
public class DomainBase
{
[Key]
public int Id { get; set; }
}
public class Project : DomainBase
{
public UserProfile User { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IList<ProjectTimeSpan> TimeSpans { get; set; }
}
[ComplexType]
public class ProjectTimeSpan
{
public DateTime TimeStart { get; set; }
public DateTime TimeEnd { get; set; }
public bool Active { get; set; }
}
}
When I try to use this action I get the exception The type 'ProjectTimer.Models.ProjectTimeSpan' has already been configured as an entity type. It cannot be reconfigured as a complex type.
public ActionResult Index()
{
using (var db = new TimerContext())
{
return View(db.Projects.ToList);
}
}
The view is using the model #model IList<ProjectTimer.Models.Project>
Can any one shine some light as to why this would be happening?
Your IList<ProjectTimeSpan> property is not supported by EF. A complex type must always be part of another entity type, you cannot use a complex type by itself. If you absolutely need to have ProjectTimeSpan as a complex type, you will need to create a dummy entity type that only contains a key and a ProjectTimeSpan, and change the type of Project.TimeSpans to a list of that new type.

Resources