0
votes

I have 2 model:

public class RentPrice
{
    public int Id { get; set; }
    public int PlaceId { get; set; }
    public System.DateTime Date { get; set; }
    public string Price { get; set; }
    public int RentTypeId { get; set; }
}

and

public class RentType
{
    public int Id { get; set; }
    public string Name { get; set; }
}

and a view model contain some property from models:

public class RentPriceViewModel
{
    public int Id { get; set; }
    public int PlaceId { get; set; }
    public string Price { get; set; }
    public string Name { get; set; }
    public DateTime Date { get; set; }
}

I use RentPriceViewModel in an another view model like this:

public class PlaceDetailsViewModel
{
    public Place Place { get; set; }
    public Place_Reserve PlaceReserve { get; set; }
    public Place_Type Place_Type { get; set; }
    public IEnumerable<Place_Type> Place_Types { get; set; }
    public Aminity Aminity { get; set; }
    public IEnumerable<Aminity> Aminities { get; set; }
    public City cities { get; set; }

    public IEnumerable<RentType> RentTypes { get; set; }
    public IEnumerable<RentPrice> RentPrices { get; set; }
    public IEnumerable<RentPriceViewModel> RentPriceViewModels { get; set; }
}

and in controller i fill this :

 PlaceDetailsViewModel pd = new PlaceDetailsViewModel();
 pd.RentTypes = db.RentTypes;
 pd.RentPriceViewModels = db.RentPrices.Join(db.RentTypes, rp => rp.RentTypeId, rt => rt.Id,
     (rp, rt) => new {rp.Id, rp.PlaceId, rp.Price, rt.Name, rp.Date})
     .Where(x => x.PlaceId == step4ViewModel.PlaceId).AsEnumerable();

but I have an error to for filling pd.RentPriceViewModels!!

Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<MazandVila.WebUI.Models.ViewModels.RentPriceViewModel>'. An explicit conversion exists (are you missing a cast?)

when I cast in Ienumerable also get error!

Please check and help me!

1
new {rp.Id, rp.PlaceId, rp.Price, rt.Name, rp.Date} should be replaced with new RentPriceViewModel {Id = rp.Id, PlaceId = rp.PlaceId, Price = rp.Price, Name = rt.Name, Date = rp.Date} - King King

1 Answers

1
votes

Problem with your code is you are assigning an anonymous type to a property whose type is RentPriceViewModels. You need to project RentPriceViewModels type instead:-

pd.RentPriceViewModels = db.RentPrices.Join(db.RentTypes, rp => rp.RentTypeId, rt => rt.Id,
      (rp, rt) => new RentPriceViewModel  { Id = rp.Id,
                                            PlaceId = rp.PlaceId, 
                                            Price = rp.Price, 
                                            Date = rt.Name, rp.Date
                                          })
      .Where(x => x.PlaceId == step4ViewModel.PlaceId).AsEnumerable();