I want to create a query that will return an AgencyContractData object containing a DocumentDto object, but it may be that the original object does not contain a foreign key on the Document. I can't use ternary operator in an Entity-Framwork LINQ query. How it is possible to implement it (Required that select be converted to sql query)?
var contractList = await query
.Select(contract => new AgencyContractData
{
ContractId = contract.Id,
ContractNumber = contract.ContractNumber,
CustomerId = contract.CustomerId,
CustomerName = contract.CustomerName,
Group = contract.Group,
CommodityType = contract.CommodityType,
SupplierName = contract.SupplierName,
StartDate = contract.StartDate,
EndDate = contract.EndDate,
ExecutionDate = contract.ExecutionDate,
ContractUnit = contract.ContractUnit,
Comment = contract.Comment,
Pricing = contract.Pricing,
SecondaryCustomerName = contract.SecondaryCustomerName,
ContractType = contract.ContractType,
AnnualVolume = contract.AnnualVolume,
Document = new DocumentDto
{
DocumentId = contract.Document.Id,
CounterPartyId = contract.Document.CounterPartyId,
FilePath = contract.Document.FilePath,
DocumentTitle = contract.Document.DocumentTitle,
IsCustomerUpload = contract.Document.IsCustomerUpload,
DocumentBytes = null
},
DocumentName = contract.DocumentName,
ContractNumberInt = contract.ContractNumberInt,
ContractNumberString = contract.ContractNumberString,
MsaBaseNumber = contract.MsaBaseNumber,
NotificationDays = contract.NotificationInDays,
State = contract.State,
CreatedOn = contract.CreatedOn,
CreatedBy = contract.CreatedBy,
ModifiedOn = contract.ModifiedOn,
ModifiedBy = contract.ModifiedBy,
It is the AgencyContract entity:
public class Contract : IEntity<long>
{
public long Id { get; set; }
public string ContractNumber { get; set; }
public long? ContractUnitId { get; set; }
public int? NumPricePeriods { get; set; }
public double? Tolerance { get; set; }
public ContractTypeEnum? ContractType { get; set; }
public ContractTolerancePeriodEnum? ContractTolerancePeriod { get; set; }
public bool IsRelyContract { get; set; }
public int TermsEndNoticeDays { get; set; }
public bool IsProrated { get; set; }
public bool IsContinuation { get; set; }
public long SupplierId { get; set; }
public long? DocumentId { get; set; }
public long? BrokerId { get; set; }
public BillTypeEnum? BillType { get; set; }
public string ExternalId { get; set; }
#region Navigation Properties
public virtual Supplier Supplier { get; set; }
public virtual Broker Broker { get; set; }
public virtual ContractUnit ContractUnit { get; set; }
public virtual Account Account { get; set; }
public virtual List<UsnAccountToContract> UsnAccountToContracts { get; set; }
public virtual List<ProviderLookup> ProviderLookups { get; set; }
public virtual List<ContractNotification> ContractNotifications { get; set; }
public virtual List<ContractVolume> ContractVolumes { get; set; }
public virtual Document Document { get; set; }
#endregion
And I want to make a AgencyContractData object using Select:
public class AgencyContractData
{
public int? AnnualVolume { get; set; }
public string Comment { get; set; }
public AgencyCommodityTypeEnum CommodityType { get; set; }
public long ContractId { get; set; }
public string ContractNumber { get; set; }
public long? ContractNumberInt { get; set; }
public string ContractNumberString { get; set; }
public int? ContractReportLevelByGlobalSearch { get; set; }
public AgencyContractTypeEnum ContractType { get; set; }
public AgencyContractUnitEnum ContractUnit { get; set; }
public Guid? CreatedBy { get; set; }
public DateTime? CreatedOn { get; set; }
public long? CustomerId { get; set; }
public string CustomerName { get; set; }
public string DocumentName { get; set; }
public DocumentDto Document { get; set; }
public DateTime? EndDate { get; set; }
public DateTime ExecutionDate { get; set; }
public string Group { get; set; }
public List<AgencyLocationData> Locations { get; set; }
public Guid? LockedBy { get; set; }
public DateTime? LockedOn { get; set; }
public string Md5Hash { get; set; }
public Guid? ModifiedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
public string MsaBaseNumber { get; set; }
public int? NotificationDays { get; set; }
public DateTime? NotificationSentOn { get; set; }
public string Pricing { get; set; }
public string SecondaryCustomerName { get; set; }
public int Sites { get; set; }
public DateTime StartDate { get; set; }
public string State { get; set; }
public string Status { get; set; }
public string SupplierName { get; set; }
I have a parent object(brand) with list of 5 child object(campaign):
Brand response = await _brandRepository.GetAsync(request.Id);
//other properties mapped fine, but Campaing is null..
var result = _mapper.Map<BrandDto>(response);
return result;
I have these definations for mapping:
CreateMap<Domain.Entity.Campaign, CampaignDto>();
CreateMap<Domain.Entity.Brand, BrandDto>();
objects:
public class BrandDto
{
public int Id { get; set; }
public string Name { get; set; }
public List<CampaignDto> Campaing { get; set; }
}
public class CampaignDto
{
public int Id { get; set; }
public int? ParentCampaignId { get; set; }
public int BrandId { get; set; }
public CampaignDto ParentCampaign { get; set; }
public BrandDto Brand { get; set; }
}
entities:
public class Brand : SqlEntityBase
{
public string Name { get; set; }
public List<Campaign> Campaign { get; set; } = new List<Campaign>();
}
public class Campaign : SqlEntityBase
{
public int? ParentCampaignId { get; set; }
public int BrandId { get; set; }
public Guid ImpressionId { get; set; }
public string Name { get; set; }
public EntryStatus Status { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime CreatedOn { get; set; }
public Brand Brand { get; set; }
public Campaign ParentCampaign { get; set; }
}
If I map child object manually it works fine, but its not cool
how can I make this proper way?
There is ICollection<InformationСontent> InformationСontents in Area class. Schema: Area -> Floor -> Place
I'd like to get all InformationContent from all Area in all Floor in all Place. How to do it?
I have only 1 linq query that returns all InformationContent in Area by id:
public async Task<IEnumerable<InformationСontent>> GetAreaInformationContentToList(int areaId)
{
// version 1
var sales = await _unitOfWork.Context.Areas.Include(x => x.Floor)
.ThenInclude(x => x.Place)
.Where(x => x.Id == areaId)
.SelectMany(x => x.InformationСontents)
.Where(x => x.ActiveTo > DateTime.Now)
.ToListAsync();
return sales;
//version 2
//var sales = await _unitOfWork.Context.Areas.FromSqlRaw("").ToListAsync();
}
public class Area
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool IsClosed { get; set; }
public string WorkingTime { get; set; }
public bool? IsLableShow { get; set; }
public bool? IsLogoShow { get; set; }
public int FloorId { get; set; }
public Floor Floor { get; set; }
public int? AreaCategoryId { get; set; }
public AreaCategory AreaCategory { get; set; }
public int? FileId { get; set; }
public FileModel File { get; set; }
public ICollection<AreaImage> AreaImages { get; set; }
public ICollection<AreaPoint> AreaPoints { get; set; }
public ICollection<InformationСontent> InformationСontents { get; set; }
}
public class Floor : IHaveId
{
public int Id { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string Name { get; set; }
public int PlaceId { get; set; }
public Place Place { get; set; }
public int? FileId { get; set; }
public FileModel File { get; set; }
public ICollection<AreaPoint> AreaPoints { get; set; }
public ICollection<Area> Areas { get; set; }
}
public class Place : BaseEntity
{
//public int Id { get; set; }
[MaxLength(150)]
public string Name { get; set; }
[MaxLength(150)]
public string Adress { get; set; }
[MaxLength(20)]
public string PhoneNumber { get; set; }
public string Description { get; set; }
public string WebSiteURL { get; set; }
public int? AreaInMeters { get; set; }
public string WorkingTime { get; set; }
public bool? IsLableShow { get; set; }
public bool? IsLogoShow { get; set; }
public bool ClockIsShowing { get; set; }
public bool TickerIsShowing { get; set; }
public string TickerText { get; set; }
public bool WeatherIsShowing { get; set; }
[Required]
public string UserId { get; set; }
public ApplicationUser User { get; set; }
public int? FileId { get; set; }
public FileModel File {get;set;}
public ICollection<Floor> Floors { get; set; }
public ICollection<StationMedia> StationMedias { get; set; }
public ICollection<AreaCategoryType> AreaCategoryTypes { get; set; }
}
public class InformationСontent : BaseEntity
{
public string Name { get; set; }
public int AreaId { get; set; }
public Area Area { get; set; }
public Byte[] Image { get; set; }
public string Description { get; set; }
public int FileId { get; set; }
public FileModel File { get; set; }
public DateTime ActiveFrom { get; set; }
public DateTime ActiveTo { get; set; }
}
I'm running into this compile error when using ThenInclude on a entity. The error is listed below. I can't see anything wrong with the relationships between the two entities. What gives, I'm banging my head against a wall here!
'ICollection<OptionType>' does not contain a definition for 'ProductOption'
and no extension method 'ProductOption' accepting a first argument of type
'ICollection<OptionType>' could be found (are you missing a using directive or
an assembly reference?)
Here are the two entities in question and related code
public async Task<ProductEditor> Edit(Expression<Func<Product, bool>> filter)
{
var product = _repo.Find(filter)
.Include(x=>x.OptionType)
.ThenInclude(x=>x.ProductOption)
public partial class OptionType
{
public OptionType()
{
ProductOption = new HashSet<ProductOption>();
}
public int OptionTypeId { get; set; }
public int ProductId { get; set; }
public string OptionName { get; set; }
public virtual ICollection<ProductOption> ProductOption { get; set; }
public virtual Product Product { get; set; }
}
public partial class ProductOption
{
public int ProductOptionId { get; set; }
public int OptionTypeId { get; set; }
public string OptionValue { get; set; }
public decimal? Price { get; set; }
public bool IsStocked { get; set; }
public virtual OptionType OptionType { get; set; }
}
public partial class Product
{
public Product()
{
EmailLog = new HashSet<EmailLog>();
OptionType = new HashSet<OptionType>();
Order = new HashSet<Order>();
ProductDiscountCode = new HashSet<ProductDiscountCode>();
ProductPaymentMethod = new HashSet<ProductPaymentMethod>();
ProductPhoto = new HashSet<ProductPhoto>();
ProductViewCounter = new HashSet<ProductViewCounter>();
ProductWishList = new HashSet<ProductWishList>();
}
public int ProductId { get; set; }
public string Title { get; set; }
public string SubTitle { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
public decimal RetailPrice { get; set; }
public decimal? SalePrice { get; set; }
public decimal ShippingCost { get; set; }
public int UserId { get; set; }
public bool WillShipInternational { get; set; }
public int QuantityTotal { get; set; }
public int QuantitySold { get; set; }
public bool IsActive { get; set; }
public bool IsBold { get; set; }
public bool IsHighlighted { get; set; }
public bool IsFeatured { get; set; }
public int ReturnPolicyId { get; set; }
public int ConditionId { get; set; }
public int StatusId { get; set; }
public DateTime CreateDate { get; set; }
public DateTime? PostedDate { get; set; }
public DateTime? EndDate { get; set; }
public virtual ICollection<EmailLog> EmailLog { get; set; }
public virtual ICollection<OptionType> OptionType { get; set; }
public virtual ICollection<Order> Order { get; set; }
public virtual ICollection<ProductDiscountCode> ProductDiscountCode { get; set; }
public virtual ICollection<ProductPaymentMethod> ProductPaymentMethod { get; set; }
public virtual ICollection<ProductPhoto> ProductPhoto { get; set; }
public virtual ICollection<ProductViewCounter> ProductViewCounter { get; set; }
public virtual ICollection<ProductWishList> ProductWishList { get; set; }
public virtual ProductCategory Category { get; set; }
public virtual ProductCondition Condition { get; set; }
public virtual ProductSystemReturnPolicy ReturnPolicy { get; set; }
public virtual ProductStatus Status { get; set; }
public virtual User User { get; set; }
I have a table in my view that a model is typed to it. However, now I need to change that model to a ViewModel (so I can Union other models on to it but one step at a time). Currently, I query my model (which works) but now I need to figure out how to convert that IEnumerable to bind it to the ViewModel (in this case, it is searchResultViewModel). I gathered what i would need to loop through each line in the IEnumerable and bind it individually (that is what the foreach loop is, me trying that) but I need to convert it back in to an 'IEnumerable'. How do I bind the IEnumerable to my ViewModel but as an 'IEnumerable'? I cannot find anyone else asking a question like this.
[HttpPost]
public ActionResult SearchResult(SearchOrders searchOrders)
{
var orderList = uni.Orders;
var model = from order in orderList
select order;
if (searchOrders.SearchStartDate.HasValue)
{
model = model.Where(o => o.OrderDate >= searchOrders.SearchStartDate);
}
if (searchOrders.SearchEndDate.HasValue)
{
model = model.Where(o => o.OrderDate <= searchOrders.SearchEndDate);
}
if (searchOrders.SearchAmount.HasValue)
{
model = model.Where(o => o.Total == searchOrders.SearchAmount);
}
var searchResultViewModel = new SearchResultViewModel();
foreach (var record in model)
{
searchResultViewModel.OrderNumber = record.OrderId;
searchResultViewModel.PaymentName = record.PaymentFullName;
searchResultViewModel.OrderDate = record.OrderDate;
searchResultViewModel.Amount = record.Total;
}
return View(model);
}
Here is my SearchOrders Model:
namespace MicrositeInfo.WebUI.Models
{
public class SearchOrders
{
public DateTime? SearchStartDate { get; set; }
public DateTime? SearchEndDate { get; set; }
public decimal? SearchAmount { get; set; }
}
}
and here is my SearchResultViewModel:
namespace MicrositeInfo.WebUI.Models
{
public class SearchResultViewModel
{
public int OrderNumber { get; set; }
public string PaymentName { get; set; }
public DateTime OrderDate { get; set; }
public decimal Amount { get; set; }
}
}
and the model that is being queried is the order model:
namespace MicrositeInfo.Model
{
[Table("Order")]
public class Order
{
public int OrderId { get; set; }
public string SelectedSession { get; set; }
public string StudentCity { get; set; }
public string StudentExtension { get; set; }
public string StudentFullName { get; set; }
public string StudentPhone { get; set; }
public string StudentPin { get; set; }
public string StudentState { get; set; }
public string StudentStreet01 { get; set; }
public string StudentStreet02 { get; set; }
public string StudentUniversityId { get; set; }
public string StudentZip { get; set; }
public string PaymentCity { get; set; }
public string PaymentCreditCardExpiration { get; set; }
public string PaymentCreditCardNumber { get; set; }
public string PaymentCreditCardSecurityCode { get; set; }
[Display(Name="Payment Name")]
public string PaymentFullName { get; set; }
public string PaymentState { get; set; }
public string PaymentStreet01 { get; set; }
public string PaymentStreet02 { get; set; }
public string PaymentZip { get; set; }
[Display(Name = "Package Id")]
[ForeignKey("Product")]
public int ProductId { get; set; }
public virtual Product Product { get; set; }
public decimal Price { get; set; }
public decimal Tax { get; set; }
public decimal Total { get; set; }
[Display(Name = "Order Date")]
public DateTime OrderDate { get; set; }
public string OrderIp { get; set; }
public string StudentEmail { get; set; }
public string PaymentId { get; set; }
public int Status { get; set; }
public string ApprovalCode { get; set; }
public decimal Shipping { get; set; }
public string STCITrackingClassCode { get; set; }
}
}