Null value in query using Select statement - c#

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

Related

AutoMapper one-to-many relationship in Entity Framework Core

I am starting to use AutoMapper. What I want is to do the following one-to-many mapping:
public class EntityEstablishment
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public int NumberParking { get; set; }
public string EstablishmentImage { get; set; }
public string EstablishmentLogoForDesktop { get; set; }
public string EstablishmentLogoForMobile { get; set; }
public string EstablishmentMap { get; set; }
public int WidthMap { get; set; }
public int HeightMap { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string Status { get; set; } = "enabled";
public bool AvailableToBooking { get; set; } = true;
public string UserId { get; set; }
public EntityUser User { get; set; }
public List<EntityEquipment> Equipments { get; set; }
public List<EntityBookableArea> BookableAreas { get; set; }
public List<EntityParking> Parkings { get; set; }
public List<EntityBankAccount> BankAccounts { get; set; }
}
public class EntityBookableArea
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public BookableAreaType Type { get; set; }
public int Capacity { get; set; }
public int StoreyNumber { get; set; }
public double ValueHour { get; set; }
public double ValueMidday { get; set; }
public double ValueDay { get; set; }
public double ValueWeek { get; set; }
public double ValueHalfMonth { get; set; }
public double ValueMonth { get; set; }
public double ValueSesion { get; set; }
public double ValueHourByStall { get; set; }
public double ValueMiddayByStall { get; set; }
public double ValueDayByStall { get; set; }
public double ValueWeekByStall { get; set; }
public double ValueHalfMonthByStall { get; set; }
public double ValueMonthByStall { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string BookableDays { get; set; }
public string BookableClass { get; set; }
public string Status { get; set; }
public double TaxPercentage { get; set; }
public bool IncludeEquipment { get; set; }
public bool IncludeParking { get; set; }
public string Coordinates { get; set; }
public List<EntityBooking> Bookings { get; set; }
public int EstablishmentId { get; set; }
public EntityEstablishment Establishment { get; set; }
}
public class EstablishmentDto
{
public int Id { get; set; }
[Required(ErrorMessage = "El nombre es requerido.")]
public string Name { get; set; }
[Required(ErrorMessage = "La ubicacion es requerida.")]
public string Location { get; set; }
public int NumberParking { get; set; }
public string EstablishmentImage { get; set; }
public string EstablishmentLogoForDesktop { get; set; }
public string EstablishmentLogoForMobile { get; set; }
public string EstablishmentMap { get; set; }
public int WidthMap { get; set; }
public int HeightMap { get; set; }
[Required]
public DateTime StartTime { get; set; }
[Required]
public DateTime EndTime { get; set; }
public string Status { get; set; } = "enabled";
public bool AvailableToBooking { get; set; } = true;
[Required(ErrorMessage = "El Administrador del establecimiento es requerido.")]
public string UserId { get; set; }
public UserDto User { get; set; }
public List<EquipmentDto> Equipments { get; set; }
public List<ParkingDto> Parkings { get; set; }
public List<BookableAreaDto> BookableAreas { get; set; }
public List<BankAccountDto> BankAccounts { get; set; }
}
How can I map the one-to-many relationship to get the information from the establishment with the BookableAreas?
I was trying the following but I get a mapping error - can you guide me on the matter?
Thank you very much for any help.
CreateMap<EntityEstablishment, EstablishmentDto>()
.ForMember(dest => dest.BookableAreas, opt => opt.MapFrom(src => src.BookableAreas))
.ForMember(dest => dest.Parkings, opt => opt.MapFrom(src => src.Parkings))

How to get all sales from all shops?

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

How to fix SQLite Constraint exception?

I am trying to insert a data in my local database (SQLited Database) using InsertAsync. But I keep getting this error.
sqlite.sqliteexception: constraint at sqlite.preparedsqlliteinsertcommand.executenonquery
How can I fix and avoid this in the future? Below is my sample code.
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
try
{
var caf_insert = new CAFTable
{
CAFNo = caf,
EmployeeID = employeenumber,
CAFDate = DateTime.Parse(date),
CustomerID = retailercode,
StartTime = DateTime.Parse(starttime),
EndTime = DateTime.Parse(endtime),
Photo1 = photo1url,
Photo2 = photo2url,
Photo3 = photo3url,
Video = videourl,
GPSCoordinates = actlocation,
Remarks = remarks,
OtherConcern = otherconcern,
RecordLog = recordlog,
LastUpdated = DateTime.Parse(current_datetime)
};
await conn.InsertOrReplaceAsync(caf_insert);
}
catch (Exception ex)
{
Crashes.TrackError(ex);
}
Here is the CAF Table
[Table("tblCaf")]
public class CAFTable
{
[PrimaryKey, MaxLength(50)]
public string CAFNo { get; set; }
[MaxLength(50)]
public string EmployeeID { get; set; }
public DateTime CAFDate { get; set; }
[MaxLength(50)]
public string CustomerID { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string Photo1 { get; set; }
public string Photo2 { get; set; }
public string Photo3 { get; set; }
public string Video { get; set; }
public string MobilePhoto1 { get; set; }
public string MobilePhoto2 { get; set; }
public string MobilePhoto3 { get; set; }
public string MobileVideo { get; set; }
[MaxLength(2000)]
public string Remarks { get; set; }
[MaxLength(2000)]
public string OtherConcern { get; set; }
[MaxLength(2000)]
public string GPSCoordinates { get; set; }
[MaxLength(100)]
public string RecordLog { get; set; }
public DateTime LastSync { get; set; }
public DateTime LastUpdated { get; set; }
public int Existed { get; set; }
public int Deleted { get; set; }
public int ThisSynced { get; set; }
public int Media1Synced { get; set; }
public int Media2Synced { get; set; }
public int Media3Synced { get; set; }
public int Media4Synced { get; set; }
}
Make sure the value of caf in your code, that you're trying to insert, does not already exist in the table.

handling circular references when saving(post)

I am stuck with an error i can't figure out. I have a complex model with several circular references. I have tried everything i know to handle them but i am still getting a internal server error (code 500) when i attempt saving.
Below are the models and controllers:
public partial class Event
{
public Event()
{
Recurrences = new HashSet<Recurrence>();
}
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Title { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
public partial class Recurrence
{
public Recurrence()
{
AspNetUsers = new HashSet<AspNetUser>();
}
public int Id { get; set; }
public int EventId { get; set; }
[Column(TypeName = "date")]
public DateTime StartDate { get; set; }
[Column(TypeName = "date")]
public DateTime? EndDate { get; set; }
public bool? AllDay { get; set; }
public TimeSpan? StartTime { get; set; }
public TimeSpan? EndTime { get; set; }
[StringLength(500)]
public string Venue { get; set; }
public double? Longitude { get; set; }
public double? Latitude { get; set; }
public int? RecurrenceInterval { get; set; }
public bool? ExcludeWeekends { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public Event Event { get; set; }
public RecurrenceType RecurrenceType { get; set; }
public ICollection<AspNetUser> AspNetUsers { get; set; }
}
public partial class AspNetUser
{
public AspNetUser()
{
Recurrences = new HashSet<Recurrence>();
}
public string Id { get; set; }
[StringLength(256)]
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
[Required]
[StringLength(256)]
public string UserName { get; set; }
public ICollection<Recurrence> Recurrences { get; set; }
}
public class EventDTO
{
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Title { get; set; }
public int EventTypeId { get; set; }
[Column(TypeName = "date")]
public DateTime StartDate { get; set; }
[Column(TypeName = "date")]
public DateTime EndDate { get; set; }
public bool? AllDay { get; set; }
public TimeSpan? StartTime { get; set; }
public TimeSpan? EndTime { get; set; }
[StringLength(500)]
public string Venue { get; set; }
public double? Longitude { get; set; }
public double? Latitude { get; set; }
public int RecurrenceTypeId { get; set; }
public int? RecurrenceInterval { get; set; }
public bool? ExcludeWeekends { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
[StringLength(128)]
public string CreatedBy { get; set; }
[StringLength(128)]
public string UpdatedBy { get; set; }
public List<string> UserId { get; set; }
}
public async Task<IHttpActionResult> PostEvent(EventDTO #event)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Event newEvent = new Event();
newEvent.Title = #event.Title;
newEvent.EventTypeId = #event.EventTypeId;
newEvent.CreateDate = #event.CreateDate;
newEvent.UpdateDate = #event.UpdateDate;
newEvent.CreatedBy = #event.CreatedBy;
newEvent.UpdatedBy = #event.CreatedBy;
if (newEvent == null) {
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Error creating Event"));
}
Recurrence recurrence = new Recurrence();
recurrence.StartDate = #event.StartDate;
recurrence.EndDate = #event.EndDate;
recurrence.AllDay = #event.AllDay;
recurrence.StartTime = #event.StartTime;
recurrence.EndTime = #event.EndTime;
recurrence.Venue = #event.Venue;
recurrence.Longitude = #event.Longitude;
recurrence.Latitude = #event.Latitude;
recurrence.RecurrenceTypeId = #event.RecurrenceTypeId;
recurrence.RecurrenceInterval = #event.RecurrenceInterval;
recurrence.ExcludeWeekends = #event.ExcludeWeekends;
recurrence.CreateDate = #event.CreateDate;
recurrence.UpdateDate = #event.UpdateDate;
recurrence.CreatedBy = #event.CreatedBy;
recurrence.UpdatedBy = #event.CreatedBy;
if (recurrence == null)
{
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, "Error creating recurrence"));
}
var users = db.AspNetUsers.Where(u => #event.UserId.Contains(u.Id));
foreach (var u in users)
recurrence.AspNetUsers.Add(u);
newEvent.Recurrences.Add(recurrence);
db.Events.Add(newEvent);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = #event.Id }, newEvent);
}
When i call the post method i get an internal error code 500 and an error message of "{$id=1, Message=An error has occurred}".

LINQ: Group by and Join

I have 2 models:
public partial class Movie
{
public Movie()
{
TimeTables = new HashSet<TimeTable>();
}
[Key]
public int MovieId { get; set; }
public string MovieName { get; set; }
public int MovieGenre { get; set; }
public string MoviePicture { get; set; }
public string MovieDescription { get; set; }
public string MovieShortText { get; set; }
public bool? MovieIs3d { get; set; }
public bool? MovieIsImax { get; set; }
public int MovieLanguage { get; set; }
public bool? MovieSubtitled { get; set; }
public int? MovieMinimalAge { get; set; }
public bool? MovieHasDrugs { get; set; }
public bool? MovieHasViolence { get; set; }
public bool? MovieHasSex { get; set; }
public bool? MovieHasSwearing { get; set; }
public bool? MovieIsScary { get; set; }
public bool? MovieHasDiscrimination { get; set; }
public string MovieTrailer { get; set; }
public int MovieLength { get; set; }
public int? Genre_GenreId { get; set; }
public int? Language_LanguageId { get; set; }
public virtual Genre Genre { get; set; }
public virtual Language Language { get; set; }
public virtual ICollection<TimeTable> TimeTables { get; set; }
}
And:
public partial class TimeTable
{
public TimeTable()
{
Reservations = new HashSet<Reservation>();
}
public int TimeTableId { get; set; }
public int MovieId { get; set; }
public int RoomId { get; set; }
public int SeatsAvaible { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public virtual Movie Movie { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
public virtual Room Room { get; set; }
}
I want to show all the records from Movie which have one or more records in TimeTable and where StartDate.date == [given datetime].
With a simple query the movies are showing multiple times. I have tried a distinct() but that changes nothing.
Anybody here who have the solution?
Current query:
var times2 =
(from s in timetablerepo.TimeTables
orderby s.StartTime.TimeOfDay
where s.StartTime.Date == datetime.Date
select s).Distinct().ToList();
Why not start with movies first and filter by timetable:
var times = timetablerepo.Movies
.Where(m => m.TimeTables.Any(t => t.StartDate.Date == <yourdate>));

Categories

Resources