Automapper with nested entity not working - asp.net-mvc

I have two classes which are mentioned below. I am trying to map those through Auto Mapper but it is not working.
public class VMTemplates
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
public System.DateTime TimeStamp { get; set; }
public virtual ICollection<VMTemplateGroup> VMTemplateGroup { get; set; }
}
public VMTemplateViewModel()
{
VMTemplateGroup = new List<VMTemplateGroupViewModel>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
[Required(ErrorMessage = "Please Upload File")]
[Display(Name = "Upload File")]
[ValidateFile]
public HttpPostedFileBase TemplateUpload { get; set; }
public System.DateTime TimeStamp { get; set; }
public List<VMTemplateGroupViewModel> VMTemplateGroup { get; set; }
I am using this code to map them
confi.CreateMap<VMTemplateViewModel, VMTemplates>().ReverseMap();
confi.CreateMap<VMTemplateGroupViewModel, VMTemplateGroup>().ReverseMap();
calling code
public VMTemplates GetVMTemplateById(int id)
{
return DataContext.VMTemplates.Include("VMTemplateGroup").Where(a => a.Id == id).FirstOrDefault();
}
This is where exception happens. I get stack overflow exception
public VMTemplateViewModel GetVMTemplateById(int templateId)
{
var result = _vmTemplateRepository.GetVMTemplateById(templateId);
return _autoMapperService.MapEntity<VMTemplateViewModel>(result);
}

Related

how to select from client model all clients thats make an order orderby Count of purchase

I want to select from client model all client without duplicate client and order them by count of the purchases they already did
This is model of client :
public class Client
{
public int ID { get; set; }
public string FacebookName { get; set; }
public string RealName { get; set; }
public string Mobile { get; set; }
public int RegionID { get; set; }
public string Addressdetails { get; set; }
public string Email { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfStart { get; set; }
public virtual Region Region { get; set; }
public virtual List<Order> order { get; set; }
}
this is Order model :
public class Order
{
public int ID { get; set; }
public int ClientID { get; set; }
public Nullable<int> ShippingID { get; set; }
public Nullable<int> SharepointID { get; set; }
public Nullable<int> CallStatuID { get; set; }
public Nullable<int> ShippingStatuID { get; set; }
public Nullable<int> ShippingStatuReasonsID { get; set; }
[DataType(DataType.Date)]
public DateTime Date { get; set; }
// public int OrderStatusID { get; set; }
public Nullable<decimal> ShippingCost { get; set; }
public string purchasetype { get; set; }
public string Notes { get; set; }
public Nullable<decimal> Discount { get; set; }
public decimal Total { get; set; }
[DefaultValue(false)]
public bool Prepared { get; set; }
[DefaultValue(false)]
public bool Done { get; set; }
[DefaultValue(false)]
public bool Shipe { get; set; }
[DefaultValue(false)]
public bool Collected { get; set; }
[DataType(DataType.Date)]
public Nullable<DateTime> DateOfCall { get; set; }
[DataType(DataType.Date)]
public Nullable<DateTime> StockCheckDate { get; set; }
[DataType(DataType.Date)]
public Nullable<DateTime> ShippingDate { get; set; }
public virtual List<OrderDetail> orderdetails { get; set; }
public virtual Client Client { get; set; }
public virtual Shipping shipping { get; set; }
public virtual Sharepoint sharepoint { get; set; }
public virtual CallStatu callStatu { get; set; }
public virtual ShippingStatu ShippingStatus { get; set; }
public virtual ShippingStatuReason ShippingStatuReasons { get; set; }
}
and finally this is OrderDetails model:
public class OrderDetail
{
public int ID { get; set; }
public int OrderID { get; set; }
public Nullable<int> ItemID { get; set; }
public Nullable<int> SizeID { get; set; }
public int ColorID { get; set; }
public decimal Price { get; set; }
public Nullable<int> StockStatuID { get; set; }
public Nullable<int> StockStatuReasonsID { get; set; }
public int Quantity { get; set; }
public decimal Total { get; set; }
public virtual Order order { get; set; }
public virtual Item item { get; set; }
public virtual Size size { get; set; }
public virtual Colors Colors { get; set; }
public virtual StockStatu stockStatus { get; set; }
public virtual StockStatuReason StockStatuReasons { get; set; }
}
I tried this way but it the select is repeat Clients If they make more than one purchase:
public JsonResult TopClientCount()
{
var index = (from dex in db.Clients
join O in db.Orders on dex.ID equals O.ClientID
select new
{
RealName = dex.RealName,
FacebookName = dex.FacebookName,
GovernorateName = dex.Region.governorate.GovernorateName,
RegionName = dex.Region.RegionName,
OrderCount = O.orderdetails.Count()
}).AsEnumerable().OrderByDescending(o => o.OrderCount)
.Distinct()
.ToList();
return Json(index, JsonRequestBehavior.AllowGet);
}
You can use let statement and you can use navigation properties i.e (order ,orderdetails) instead of joins
var index = (from dex in db.Clients
//This will give you all the order details for a client
let orderDetails = dex.order.SelectMany(p=> p.orderdetails)
select new
{
RealName = dex.RealName,
FacebookName = dex.FacebookName,
GovernorateName = dex.Region.governorate.GovernorateName,
RegionName = dex.Region.RegionName,
OrderCount = orderDetails.Count()
}).AsEnumerable().OrderByDescending(o => o.OrderCount)
.Distinct()
.ToList();

Object reference error when getting data from database

My portal has worked fine for several years but nowadays I have problems with my some codes. I want to update my code but at the first step I have problems with login page. when I use FirstOrDefault I got error on object reference while the list is filled and contains 1 user.
int g = db.sp_GetUserData_ByUserName(model.UserName.Trim()).Count();
//it shows 1
OSUserData userData1 = db.sp_GetUserData_ByUserName(model.UserName.Trim()).FirstOrDefault();
I didn't change this code and It works perfectly on the portal. However, I can't run it on my development server.
I checked again and I found that OSUserData constructor throws exception : Enumeration yielded no result. this is my class code :
public OSUserData()
{
this.OSUploadedFilesMultipleUsers = new HashSet<OSUploadedFilesMultipleUser>();
this.OSSalaryLists = new HashSet<OSSalaryList>();
this.OSUploadedFiles = new HashSet<OSUploadedFile>();
}
public int Id { get; set; }
public string Address { get; set; }
public string BranchCode { get; set; }
public string BranchParentNationalCode { get; set; }
public string CitName { get; set; }
public string City { get; set; }
public string CompanyName { get; set; }
public string CouName { get; set; }
public string Country { get; set; }
public string FaxNo { get; set; }
public string FollowCode { get; set; }
public string Hozeh { get; set; }
public Nullable<bool> IsBranch { get; set; }
public string LoginStatus { get; set; }
public string NationalCode { get; set; }
public string NewEconomicNo { get; set; }
public string Oldeconomicno { get; set; }
public string PostalCode { get; set; }
public string ProIdTTMS { get; set; }
public string ProName { get; set; }
public string Provision { get; set; }
public string RegistrationNo { get; set; }
public string State { get; set; }
public string TaxOfficeCode { get; set; }
public string TaxPayerType { get; set; }
public string TelCode { get; set; }
public string TelNo { get; set; }
public string TprId { get; set; }
public string UserName { get; set; }
public bool Validate { get; set; }
public bool Disabled { get; set; }
public string OwnerShipTypeDesc { get; set; }
public Nullable<byte> OwnerShipTypeCode { get; set; }
public bool Processed { get; set; }
public bool CheckedUser { get; set; }
public bool Blocked { get; set; }
public virtual ICollection<OSUploadedFilesMultipleUser> OSUploadedFilesMultipleUsers { get; set; }
public virtual ICollection<OSSalaryList> OSSalaryLists { get; set; }
public virtual ICollection<OSUploadedFile> OSUploadedFiles { get; set; }
You are trying to add to a null/unreferenced/not initialized object/list. Initialize first the list
List<OSUserData> userData1 = new List<OSUserData>();
Then add it
var user = db.sp_GetUserData_ByUserName(model.UserName.Trim()).FirstOrDefault();
userData1.Add(new OSUserData{
Prop1 = user.Prop1,
Prop2 = user.Prop2,
......
});
Or if you only want one user, just make it var
var user = db.sp_GetUserData_ByUserName(model.UserName.Trim()).FirstOrDefault();

Eager loading with include method does not return data from collection

I wanted to eager load a collection but it does not returns any data
I have tried nothing
//here is my controller
var accountGroup = await db.AccountGroups.Include(a=>a.AccountGroupTypes)
.Include(a=>a.AccountPrimaryGroups).ToListAsync();
//here is my model
public int? Id { get; set; }
public string Name { get; set; }
public int AccountGroupTypeId { get; set; }
public ICollection<AccountGroupType> AccountGroupTypes { get; set; }
public int AccountPrimaryGroupId { get; set; }
public ICollection<AccountPrimaryGroup> AccountPrimaryGroups { get; set; }
public DateTime CreationDateUtcNow{ get; set; }
It returns AccountGroupData but It does not return AccountGroupTypes and AccountPrimaryGroup data
Mark your AccountGroupTypes and AccountPrimaryGroups as virtual properties and be sure that you have a parameterless constructor which is initializing those properties.
public int? Id { get; set; }
public string Name { get; set; }
public int AccountGroupTypeId { get; set; }
public vitual ICollection<AccountGroupType> AccountGroupTypes { get; set; }
public int AccountPrimaryGroupId { get; set; }
public virtual ICollection<AccountPrimaryGroup> AccountPrimaryGroups { get; set; }
public DateTime CreationDateUtcNow{ get; set; }
public AccountGroup()
{
this.AccountGroupTypes = new HashSet<AccountGroupType>();
this.AccountPrimaryGroups = new HashSet<AccountPrimaryGroups>();
}

MVC model value becomes null on post back

I am getting null value for the model on postback.I am not able to find out where I am going wrong.I have seen similar questions but couldn't find any solution yet.
Here is my code:
Controller:
public ActionResult ContactUpdate(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
string[] testsplit = id.Split(',');
List<int> intTest = new List<int>();
foreach (string s in testsplit)
intTest.Add(int.Parse(s));
ObjectParameter ObjParam = new ObjectParameter("ErrorCode", 0);
var cont = db.spErrorContactGet(365, ObjParam);
var ToBeUpdated = (from contacts in cont
where intTest.Contains(contacts.ResponseID)
select contacts);
IEnumerable<spErrorContactGet_Result> Update = ToBeUpdated.ToList();
return View(Update);
}
[HttpPost]
public ActionResult ContactUpdate(List<spErrorContactGet_Result> Res)
{
if (Res == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do something
// redirect to another view
}
Here is the model class:
public class spErrorContactGet_Result
{
public int ResponseID { get; set; }
public string ContactAlchemyMessage { get; set; }
public string ContactTeamAlchemyMessage { get; set; }
public string ContactElectronicAddressAlchemyMessage { get; set; }
public string ContactAccountAlchemyMessage { get; set; }
public string CRMContactID { get; set; }
public string InfluenceLevel { get; set; }
public string JobRole { get; set; }
public string Department { get; set; }
public string DepartmentName { get; set; }
public string MobilePhone { get; set; }
public string Email { get; set; }
public string Suffix { get; set; }
public string FaxNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string JobTitle { get; set; }
public string HonorablePrefix { get; set; }
public string Prefix { get; set; }
public string ContactAuthPhoneId { get; set; }
public string ContactAuthDmailId { get; set; }
public string ContactAuthEmailId { get; set; }
public string AllowFax { get; set; }
public string PartnerContactAuthPhoneID { get; set; }
public string PartnerContactAuthDmailID { get; set; }
public string PartnerContactAuthEmailID { get; set; }
public string PrivacyStatementReviewed { get; set; }
public string PreferredLanguage { get; set; }
public string IndWorkPhone { get; set; }
public string FullNamePronunciation { get; set; }
public string CRMOwner { get; set; }
public string KeyContact { get; set; }
public string MarketingAudience { get; set; }
public bool IsSelected { get; set; }
}
}
I am unable to post the view in the right format.
It is likely that structure of your view differs from one that is of your model, they must syntactically match. If you would post your view it could help. BTW there is no 'Postback' in MVC

TableName.RowName retrieves Nothing in MVC

I have a model class called "KelimeTuru" designed as shown below:
public partial class KelimeTuru
{
public int Id { get; set; }
public int KelimeId { get; set; }
public int MenseiId { get; set; }
public int TurId { get; set; }
public int AnlamTurleriId { get; set; }
public int SozlukTuruId { get; set; }
public Nullable<int> SesId { get; set; }
public Nullable<int> VideoId { get; set; }
public Nullable<int> ResimId { get; set; }
public Nullable<int> SembolId { get; set; }
public Nullable<int> BirimId { get; set; }
public Nullable<int> SimgeId { get; set; }
public string Anlam { get; set; }
public string Transkript { get; set; }
public virtual AnlamTurleri AnlamTurleri { get; set; }
public virtual Birim Birim { get; set; }
public virtual Kelime Kelime { get; set; }
public virtual Mensei Mensei { get; set; }
public virtual Sembol Sembol { get; set; }
public virtual Ses Ses { get; set; }
public virtual Simge Simge { get; set; }
public virtual SozlukTuru SozlukTuru { get; set; }
public virtual Turler Turler { get; set; }
public virtual Video Video { get; set; }
public virtual Resim Resim { get; set; }
}
And It retrieves the required data if we use the Id of the record properly like this:
public ActionResult Details(int id=0)
{
SozlukEntities db = new SozlukEntities();
KelimeTuru kelime = db.KelimeTuru.Find(id);
if (kelime == null)
{
return HttpNotFound();
}
return View(kelime);
}
I want to retrieve records according to their "KelimeId"s not "Id"s so replaced the word "id" with "KelimeId" in my code. But got a "404.0 - Not Found" error.
Could you please help me retrieve "KelimeTuru" table using KelimeId?
try this:
KelimeTuru kelime = db.KelimeTuru.SingleOrDefault(x => x.KelimeId == id);
Find method works only on Primary Key Property, means if your property is decorated with [Key] attribute, then Find() will be able to find record, otherwise it wil not fetch the record.
It sounds like you want something like this:
KelimeTuru kelime = db.KelimeTuru.Where(x => x.KelimeId == id).SingleOrDefault();

Resources