AutoMapper Many to Many relationship - asp.net-mvc

I'm not sure where I'm going wrong here. I want to map my classes so that there aren't extra levels in the returned values.
Models (DTOs):
public class FilmViewModel
{
public FilmViewModel() { }
public int Id { get; set; }
[Required(ErrorMessage = "Naziv filma je obavezno polje.")]
public string Naziv { get; set; }
public string Opis { get; set; }
public string UrlFotografije { get; set; }
[RegularExpression(#"^(19|20)[\d]{2,2}$", ErrorMessage = "Godina mora biti u YYYY formatu.")]
public int Godina { get; set; }
public JezikEnum Jezik { get; set; }
public int Trajanje { get; set; }
public bool IsActive { get; set; }
public List<Licnost> Licnosti { get; set; }
}
public class LicnostViewModel
{
public LicnostViewModel() { }
public int Id { get; set; }
[Required]
public string ImePrezime { get; set; }
[Required]
public bool IsGlumac { get; set; }
[Required]
public bool IsRedatelj { get; set; }
public List<Film> Filmovi { get; set; }
}
Entities:
public class Film
{
[Key]
public int Id { get; set; }
[Required]
public string Naziv { get; set; }
public string Opis { get; set; }
public string UrlFotografije { get; set; }
[RegularExpression(#"^(19|20)[\d]{2,2}$")]
public int Godina { get; set; }
public JezikEnum Jezik { get; set; }
public bool IsActive { get; set; }
public int Trajanje { get; set; }
public List<FilmLicnost> Licnosti { get; set; }
}
public class Licnost
{
[Key]
public int Id { get; set; }
[Required]
public string ImePrezime { get; set; }
[Required]
public bool IsGlumac { get; set; }
[Required]
public bool IsRedatelj { get; set; }
public List<FilmLicnost> Filmovi { get; set; }
}
public class FilmLicnost
{
[Key]
public int Id { get; set; }
[ForeignKey(nameof(Licnost))]
public int LicnostId { get; set; }
public Licnost Licnost { get; set; }
[ForeignKey(nameof(Film))]
public int FilmId { get; set; }
public Film Film { get; set; }
}
Basically Swagger already shows me what I'm returning, but I want to avoid unnecessary nesting. It's marked in the image:
I want to say that I've been looking all over SO, AutoMapper documentation etc. No answer/example finds me the solution I need. I'm either missing a Model(DTO) somewhere or there is something major wrong with my logic.
Some example links that I tried are this and this
Also here are some links I tried to get information from: link1, link2
This is what I've tried so far:
CreateMap<FilmLicnost, LicnostViewModel>()
.ForMember(dest => dest.Filmovi, dest => dest.MapFrom(x => x.Film))
.AfterMap((source, destination) =>
{
if (destination?.Filmovi == null) return;
foreach (var temp in destination.Filmovi)
{
temp.Id = source.Film.Id;
temp.IsActive = source.Film.IsActive;
temp.Jezik = source.Film.Jezik;
temp.Naziv = source.Film.Naziv;
temp.Opis = source.Film.Opis;
temp.Godina = source.Film.Godina;
temp.Trajanje = source.Film.Trajanje;
temp.UrlFotografije = source.Film.UrlFotografije;
}
});
CreateMap<FilmLicnost, FilmViewModel>()
.ForMember(dest => dest.Licnosti, dest => dest.MapFrom(x => x.Licnost))
.AfterMap((source, destination) =>
{
if (destination?.Licnosti == null) return;
foreach (var temp in destination?.Licnosti)
{
temp.Id = source.Licnost.Id;
temp.ImePrezime = source.Licnost.ImePrezime;
temp.IsGlumac = source.Licnost.IsGlumac;
temp.IsRedatelj = source.Licnost.IsRedatelj;
}
});
Also this:
CreateMap<FilmLicnost, Film>()
.ForMember(dest => dest.Licnosti, dest => dest.Ignore());
CreateMap<FilmLicnost, Licnost>()
.ForMember(dest => dest.Filmovi, dest => dest.Ignore());
Note I have already defined the mapping for Entities:
CreateMap<Film, FilmViewModel>();
CreateMap<FilmViewModel, Film>();
CreateMap<Licnost, LicnostViewModel>();
CreateMap<LicnostViewModel, Licnost>();

Related

how to get stock value by size and quantity and color one shot

I have four models ( Item, Fabric, Production, stock)
and i want to get value of stock by item ID like that :
<table class="table-responsive">
<tr>
<td>Color</td>
<td>Size</td>
<td>Quantity</td>
</tr>
<tbody class="StockTbody"></tbody>
</table>
so that the values for the color and size are not repeated.
fabric Model:
public class Fabric
{
public int ID { get; set; }
public string FabricName { get; set; }
//[DataType(DataType.Date)]
[Display(Name = "Color")]
public int ColorID { get; set; }
public string Code { get; set; }
public virtual Colors Colors { get; set; }
public virtual List<FabricStore> fabricStore { get; set; }
public virtual List<Production> production { get; set; }
}
Color Model:
public class Colors
{
public int ID { get; set; }
[Display(Name ="Color")]
public string ColorName { get; set; }
public virtual List<Fabric> fabric { get; set; }
public virtual List<OrderDetail> OrderDetails { get; set; }
}
Item Model :
public class Item
{
public int ID { get; set; }
[Display(Name = "Item")]
public string ItemName { get; set; }
public int code { get; set; }
[Display(Name ="Collection")]
public Nullable<int> CollectionID { get; set; }
[Display(Name = "Category")]
public Nullable<int> CategoryID { get; set; }
public string Image { get; set; }
public string BarcodeImage { get; set; }
public string Barcode { get; set; }
public int NumberOfDraft { get; set; }
public decimal SectoralSellingPrice { get; set; }
public decimal wholesalePrice { get; set; }
public decimal discountPrice { get; set; }
public decimal wholesalevariegated { get; set; }
public decimal DesignCost { get; set; }
public int three { get; set; }
public virtual List<Production> production { get; set; }
public virtual Collection collection { get; set; }
public virtual Categories categories { get; set; }
public virtual List<OrderDetail> orderDetail { get; set; }
}
and this is stock model:
public class Stock
{
public int ID { get; set; }
public int ProductionID { get; set; }
public int SizeID { get; set; }
public int Quantity { get; set; }
public string ShelfNumber { get; set; }
public virtual Production Production { get; set; }
public virtual Size size { get; set; }
public virtual List<StockRemain> stockRemain { get; set; }
}
this is my Controller:
public JsonResult StuckDetails (int ID)
{
var table = (from tb in db.Stocks
where ID == tb.Production.ItemID
select new
{
color = tb.Production.fabric.Colors.ColorName,
ColorId=tb.Production.fabric.ColorID,
size = tb.size.SizeName,
sizeID = tb.SizeID,
//Quantity =
}).Distinct().ToList();
return Json(table, JsonRequestBehavior.AllowGet);
}
the problem is that : i want to sum Quantity
please help
I think you are looking for a group by here:
public JsonResult StuckDetails (int ID)
{
var table = (from tb in db.Stocks
where ID == tb.Production.ItemID
group tb by new
{
tb.Production.fabric.Colors.ColorName,
tb.size.SizeName
} into grp
select new
{
color = grp.Key.ColorName,
size = grp.Key.SizeName,
Quantity = grp.Sum(g => g.Quantity)
});
return Json(table, JsonRequestBehavior.AllowGet);
}
They Key.ColorName property name might vary - I'm not too sure here. Use Intellisense to guide you through it.

Automapper with nested entity not working

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);
}

Many to Many Relationship in MVC 5 EF6

Im using MVC 5 and EF 6.
There are 3 tables in my code: "Leads", "Phones", "LeadStatus" and a junction table "LeadPhones".
I want to show following properties in Index View:
Leads.FullName
LeadStatus.Status
Phones.PhoneID
How should I configure the LeadController?
public partial class Leads
{
public Leads()
{
this.LeadPhones = new HashSet<LeadPhones>();
}
[Key]
public int LeadID { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return NamePrefix + " " + FirstName + " " + LastName; } }
public int LeadStatusID { get; set; }
public virtual LeadStatus LeadStatus { get; set; }
public virtual ICollection<LeadPhones> LeadPhones { get; set; }
}
and
public partial class Phones
{
public Phones()
{
this.AccountPhones = new HashSet<AccountPhones>();
this.ContactPhones = new HashSet<ContactPhones>();
this.EmployeePhones = new HashSet<EmployeePhones>();
this.LeadPhones = new HashSet<LeadPhones>();
}
[Key]
public int PhoneID { get; set; }
public string PhoneNo { get; set; }
public virtual ICollection<LeadPhones> LeadPhones { get; set; }
}
and
public partial class LeadPhones
{
[Key]
public int LeadPhoneID { get; set; }
public int LeadID { get; set; }
public int PhoneID { get; set; }
public virtual Leads Leads { get; set; }
public virtual Phones Phones { get; set; }
}
and
public partial class LeadStatus
{
public LeadStatus()
{
this.Leads = new HashSet<Leads>();
}
[Key]
public int LeadStatusID { get; set; }
public string Status { get; set; }
public virtual ICollection<Leads> Leads { get; set; }
}
the following does not work:
public ActionResult Index()
{
var leads = db.Leads.Include(l => l.LeadStatus).Include(l => l.LeadPhones);
return View(leads);
}
The main problem is the "PhoneNo". How could I get that from a junction table?
Remove the LeadPhoneID column from the LeadPhones table -- It isn't necessary and will only cause problems for you. Remove all references to LeadPhones in your classes. Leads a virtual property to Phones (not LeadPhones). LeadPhones has a virtual property to Leads (not LeadPhones).
After you do that, then you should be able to:
var leads = db.Leads.Include(l => l.LeadStatus).Include(l => l.Phones);
public partial class Lead
{
public Lead()
{
this.Phones = new HashSet<Phone>();
}
[Key]
public int LeadID { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return NamePrefix + " " + FirstName + " " + LastName; } }
public int LeadStatusID { get; set; }
public virtual LeadStatus LeadStatus { get; set; }
public virtual ICollection<Phone> Phones { get; set; }
}
public partial class Phone
{
public Phone()
{
this.AccountPhones = new HashSet<AccountPhones>();
this.ContactPhones = new HashSet<ContactPhones>();
this.EmployeePhones = new HashSet<EmployeePhones>();
this.Leads = new HashSet<Lead>();
}
[Key]
public int PhoneID { get; set; }
public string PhoneNo { get; set; }
public virtual ICollection<Lead> Leads { get; set; }
}
public partial class LeadStatus
{
public LeadStatus()
{
this.Leads = new HashSet<Lead>();
}
[Key]
public int LeadStatusID { get; set; }
public string Status { get; set; }
public virtual ICollection<Lead> Leads { get; set; }
}
I've also corrected the plurality of your classes. Lead vs Leads. The class describes a single lead, so it should be called Lead not Leads. Phone vs Phones.

Automapper mapping issue

I need to map a model to a viewmodel using AutoMapper.
Model:
[Table("News")]
public class News
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public DateTime DatePostedOn { get; set; }
public int Position { get; set; }
public Category Category { get; set; }
public virtual ICollection<Picture> Pictures { get; set; }
}
[Table("Pictures")]
public class Picture
{
[Key]
public int Id { get; set; }
public DateTime DateCreated { get; set; }
public string Filename { get; set; }
public int Type { get; set; }
public virtual ICollection<News> News { get; set; }
}
Viewmodel:
public class HomeViewModels
{
public IList<HomeMainNews> MainNews { get; private set; }
}
public class HomeMainNews
{
public int Id { get; set; }
public string Title { get; set; }
public string Date { get; set; }
public string PictureURL { get; set; }
}
Mapping:
Mapper.CreateMap<News, HomeMainNews>();
How can I map a News that have a set of Pictures, to a viewmodel with only one picture according to a certain condition "Type = 2"
Current solution:
vm.MainNews = db.News
.Select(n => new HomeMainNews {
Id = n.Id,
Date = n.DatePostedOn.ToString(),
Title = n.Title,
PictureURL = n.Pictures.Where(p => p.Type == 1).Select(p => p.Filename).FirstOrDefault().ToString()
}).ToList();
Automapper solution:
vm.MainNews = db.News.Project().To<HomeMainNews>().ToList();
Try this
Mapper.CreateMap<News, HomeMainNews>()
.ForMember(mainNew => mainNew.Date, opt => opt.MapFrom(news => news.DatePostedOn))
.ForMember(mainNew => mainNew.PictureURL, opt => opt.MapFrom(news => news.Pictures.First(pic => pic.Type == 2).Filename));

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

Resources