What is the best way to combine multiple DbQuery results? - c#
I am creating a massive grid that displays all of the different record types across 4 table in my database. I have created a viewmodel that holds every field from each record type, and then did a query to get each of them, and create a viewmodel object for each. I now want to combine all of these into one big result, and return to my View so that I can display everything in the grid. Here is my function for getting all log types:
public ActionResult GetAllLogs([DataSourceRequest]DataSourceRequest request)
{
//var result;
var allAssetConfigLogs = DbContext.AssetConfigurations.Select(log => new Models.AllLogsViewModel()
{
ID = log.Asset_SK.Value,
AssetConfigurationID = log.AssetConfiguration_SK,
AssetID = log.Asset_SK.Value,
AssetName = log.Asset.Name,
RedConID = log.ReadinessCondition_SK,
RedCon = log.ReadinessCondition.Name,
EKVType = log.EKV_Type_SK,
IsSSF = log.IsSSF,
IsArmedPlug = log.IsArmedPlug,
IsConnectedCommunications = log.IsConnectedCommunications,
IsFutureCapable = log.IsFutureCapable,
IsFutureCapableLongTerm = log.IsFutureCapableLongTerm,
IsActive = log.IsActive,
IsExternal = log.IsExternal,
IsIsolationComponent = log.IsIsolationComponent,
IsIsolationSerial = log.IsIsolationSerial,
IsInMaintenanceMode = log.IsInMaintenanceMode,
IsEWCS = log.IsEWCS,
IsMBIT = log.IsMBIT,
IsIcoBsc = log.IsIcoBsc,
IsLocal = log.IsLocal,
IsStop = log.IsStop,
IsSurge = log.IsSurge,
ACNotes = log.Notes,
SoftwareVersion = log.SoftwareVersion,
IsIsolationSwitchPort = log.IsIsolationSwitchPort,
IsPortManagedDown = log.IsPortManagedDown,
IsOsfLogical = log.IsOsfLogical,
ShipName = log.ShipName,
JUNumber = log.JU_Number,
GMACKey = log.GMAC_Key,
URN = log.URN,
TimeStamp = log.TimeStamp,
});
var allMissionLogs = DbContext.MissionConfigurations.Select(log => new Models.AllLogsViewModel()
{
MissionConfiguration_SK = log.MissionConfiguration_SK,
Asset_SK = log.Asset_SK,
EventType_SK = log.EventType_SK,
Environment_SK = log.Environment_SK,
RedConID = log.ReadinessCondition_SK,
RecallTime = log.RecallTime,
Notes = log.Notes
});
var allPACLogs = DbContext.PAC_Logs.Select(log => new Models.AllLogsViewModel()
{
UserRole = String.Join(",", log.User.Roles),
PacLogID = log.PAC_Log_SK,
SiteID = log.Site_SK,
PacLogStatusID = log.PAC_LogStatus_SK,
Status = log.PAC_LogStatus.Description,
StatusDate = log.StatusDate,
ActivityDescription = log.ActivityDescription,
ActivityDetailDescription = log.ActivityDetailDescription,
TrackingNumber = log.TrackingNumber,
QuickTrack = log.QuickTrack,
WAM_Number = log.WAM_Number,
WAM_Revision = log.WAM_Revision,
RequestedBy = log.RequestedBy,
RequestedByName = log.User1 != null ? log.User1.FirstName + " " + log.User1.LastName : "",
Controller = log.Controller,
ControllerName = log.User2 != null ? log.User2.FirstName + " " + log.User2.LastName : "",
AuthorizationNumber = log.AuthorizationNumber,
IsSafe = log.IsSafe,
SafeComments = log.SafeComments,
PlanStartZulu = log.PlanStartZulu,
PlanFinishZulu = log.PlanFinishZulu,
ActualStartZulu = log.ActualStartZulu,
ActualFinishZulu = log.ActualFinishZulu,
PlanStartLocal = log.PlanStartLocal,
PlanFinishLocal = log.PlanFinishLocal,
ActualStartLocal = log.ActualStartLocal,
ActualFinishLocal = log.ActualFinishLocal,
IsGovDirected = log.IsGovernmentDirected,
POC = log.POC,
POCPhone = log.POC_Phone,
WorkOrder = log.WorkOrder,
ApprovalAuthority = log.ApprovalAuthority,
AuthorityDocument = log.AuthorityDocument,
FinalVerification = log.FinalVerification,
WindowActivity = log.WindowActivities,
APAC = log.APAC,
WAMStartZulu = log.WAMStartZulu,
WAMFinishZulu = log.WAMFinishZulu,
AssetAvailable = log.AssetAvailable,
AssetUnavailable = log.AssetUnavailable,
AssetStatus = log.MaintenanceStatus_SK,
AssetStatusString = log.MaintenanceStatu.Name,
ID_MaintenanceActivity = log.MaintenanceActivity_SK,
ID_MaintenanceActivityString = log.MaintenanceActivity.Name,
FourtyMinuteNotification = log.C40MinNotification,
Comments = log.Comments,
QAComments = log.QA_Comments,
QACheck = log.QA_Check,
Unscheduled = log.Unscheduled,
SiteName = log.Site.FullName,
Environment1 = log.Environment1,
Environment2 = log.Environment2,
Environment3 = log.Environment3,
TimeZoneID = log.TimeZone_SK,
TimeZone = log.TimeZone.Name,
TimeZoneOffset = log.TimeZone_SK != null ? log.TimeZone.Offset.Value : 0,
AssetCheck = log.AssetLogPAC_Logs.Count > 0 ? "yes" : "",
EnvironmentCheck = log.Environment1 || log.Environment2 || log.Environment3 ? "yes" : ""
});
var allPRs = DbContext.ProblemReports.Select(log => new Models.AllLogsViewModel()
{
ProblemReportID = log.ProblemReport_SK,
ProblemReportOwnerID = log.ProblemReportOwner_SK,
EventID = log.Event_SK,
EventString = log.Event.Name,
SubAssembly = log.Subassembly_SK,
SubAssemblyString = log.Subassembly.Name,
ActualFailureTime = log.ActualFailureTime,
ActualRestoreTime = log.ActualRestoreTime,
CurrentDateTimeGroup = log.CurrentDateTimeGroup,
FaultEventDescription = log.FaultEventDescription,
FaultEventDetails = log.FaultEventDetails,
CurrentDayActivities = log.CurrentDayActivities,
PathForward = log.PathForward,
EstimatedArrivalDate = log.EstimatedArrivalDate,
WorkOrderNumber = log.WorkOrderNumber,
NCR_Number = log.NCR_Number,
MalfunctionNotes = log.MalfunctionNotes,
RepairStatus = log.RepairStatus,
NextUpdateDue = log.NextUpdateDue,
OriginatedBy = log.OriginatedBy,
OriginatedByString = log.User.FirstName + " " + log.User.LastName,
ReleasedBy = log.ReleasedBy,
ReleasedByString = log.ReleasedBy != null ? log.User1.FirstName + " " + log.User1.LastName : "",
ClosedBy = log.ClosedBy,
ClosedByString = log.ClosedBy != null ? log.User2.FirstName + " " + log.User2.LastName : "",
IsClosed = log.IsClosed,
IsNotesVisible = log.IsNotesVisible,
TimeStamp = log.TimeStamp,
RedConID = log.ReadinessCondition_SK,
RedCon = log.ReadinessCondition.Name,
AssetType = log.Asset.AssetType.Name,
AssetSite = log.Asset.Site.Name,
Rev = log.ProblemReportDetails.OrderByDescending(x => x.CreatedBy).FirstOrDefault().Revision.Name,
ETRO = log.ProblemReportDetails.OrderByDescending(x => x.CreatedBy).FirstOrDefault().ETRO.ToString(),
ETROChangeReason = log.ProblemReportDetails.OrderByDescending(x => x.CreatedBy).FirstOrDefault().ETRO_ChangeReasons.Name,
NoteArchive = log.NotesArchive,
currentDetail = log.ProblemReportDetails.OrderByDescending(y => y.CreatedOn).FirstOrDefault(),
RelatedAssetEnv = DbContext.MissionConfigurations.Where(y => y.Asset_SK == log.Asset.Asset_SK).OrderByDescending(y => y.TimeStamp).Select(y => y.Environment.EnvironmentLogs.OrderByDescending(z => z.TimeStamp).FirstOrDefault().Designation).FirstOrDefault()
});
//return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
My Giant ViewModel (Combining different fields from different log types into one big model):
`//This is a model of all log types (relating to assets) consolidated into one.
public class AllLogsViewModel
{
//This region holds fields that are shared amongst multiple log types.
#region SharedFields
public int ID { get; set; }
public string RedCon { get; set; }
public int RedConID { get; set; }
public DateTime TimeStamp { get; set; }
public string TimeStampString
{
get { return TimeStamp.ToString(); }
}
public string TimeStampStringZulu
{
get { return TimeStamp.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedOnString
{
get { return CreatedOn.ToString(); }
}
public string CreatedOnStringZulu
{
get { return CreatedOn.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public string UpdatedBy { get; set; }
public DateTime UpdatedOn { get; set; }
public string UpdatedOnString
{
get { return UpdatedOn.ToString(); }
}
public string UpdatedOnStringZulu
{
get { return UpdatedOn.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
#endregion
#region AssetConfigLogs
public int AssetConfigurationID { get; set; }
public int AssetID { get; set; }
public string AssetName { get; set; }
public int EKVType { get; set; }
//Labeled as "OSF Physical" for some reason?
public bool IsSSF { get; set; }
public bool IsArmedPlug { get; set; }
public bool IsArmedSDS { get; set; }
public bool IsConnectedCommunications { get; set; }
public bool IsFutureCapable { get; set; }
public bool IsFutureCapableLongTerm { get; set; }
public bool IsActive { get; set; }
public bool IsExternal { get; set; }
public bool IsIsolationComponent { get; set; }
public bool IsIsolationSerial { get; set; }
public bool IsInMaintenanceMode { get; set; }
public bool IsEWCS { get; set; }
public bool IsMBIT { get; set; }
public bool IsIcoBsc { get; set; }
public bool IsLocal { get; set; }
public bool IsStop { get; set; }
public bool IsSurge { get; set; }
public string ACNotes { get; set; }
public string SoftwareVersion { get; set; }
public bool IsIsolationSwitchPort { get; set; }
public bool IsPortManagedDown { get; set; }
public bool IsOsfLogical { get; set; }
public string ShipName { get; set; }
public string JUNumber { get; set; }
public string GMACKey { get; set; }
public string URN { get; set; }
//form logic controls?
public bool GMMVisibility { get; set; }
public bool CNEVisibility { get; set; }
public bool SiloVisibility { get; set; }
public bool IDTVisibility { get; set; }
public bool AEGISVisibility { get; set; }
public bool GMACVisibility { get; set; }
public bool URNVisibility { get; set; }
public bool ANTPY2Visibility { get; set; }
public bool GBIVisibility { get; set; }
public bool OSFVisibility { get; set; }
public bool PortIsolationVisibility { get; set; }
public int AssignedGBIID { get; set; }
public string AssignedGBIName { get; set; }
public int AssignedCNEID { get; set; }
public string AssignedCNEName { get; set; }
#endregion
#region MissionLogs
public int MissionConfiguration_SK { get; set; }
public int Asset_SK { get; set; }
public int EventType_SK { get; set; }
public int Environment_SK { get; set; }
public string Designation
{
get
{
var designation = string.Empty;
switch (EventType_SK)
{
case 5: designation = "COMM";
break;
case 8: designation = "OPS";
break;
case 10: designation = "TEST";
break;
}
return designation;
}
} //For EventType_SK
public int RecallTime { get; set; }
public string Notes { get; set; }
#endregion
#region PacLogs
public string UserRole { get; set; }
public string SubmitType { get; set; }
public int PacLogID { get; set; }
public int SiteID { get; set; }
public int? PacLogStatusID { get; set; }
public string Status { get; set; }
public DateTime StatusDate { get; set; }
public string StatusDateString
{
get { return StatusDate.ToString(); }
}
[DisplayName("Status Date")]
public string StatusDateStringZulu
{
get { return StatusDate.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public string ActivityDescription { get; set; }
public string ActivityDetailDescription { get; set; }
public string TrackingNumber { get; set; }
public string QuickTrack { get; set; }
public string WAM_Number { get; set; }
public string WAM_Revision { get; set; }
public int? RequestedBy { get; set; }
public string RequestedByName { get; set; }
public int? Controller { get; set; }
public string ControllerName { get; set; }
public string AuthorizationNumber { get; set; }
public bool IsSafe { get; set; }
public string SafeComments { get; set; }
public DateTime? PlanStartZulu { get; set; }
[DisplayName("Planned Start")]
public string PlanStartZuluString
{
get { return PlanStartZulu?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
[Required(ErrorMessage = "Planned Close is Required")]
// changed to "Planned Close"
public DateTime? PlanFinishZulu { get; set; }
[DisplayName("Planned Close")]
public string PlanFinishZuluString
{
get { return PlanFinishZulu?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public DateTime? ActualStartZulu { get; set; }
[DisplayName("Actual Start")]
public string ActualStartZuluString
{
get { return ActualStartZulu?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public DateTime? ActualFinishZulu { get; set; }
[DisplayName("Actual Close")]
public string ActualFinishZuluString
{
get { return ActualFinishZulu?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public DateTime? PlanStartLocal { get; set; }
[DisplayName("Planned Start(Local)")]
public string PlanStartLocalString
{
get { return PlanStartLocal?.ToString(); }
}
public DateTime? PlanFinishLocal { get; set; }
[DisplayName("Planned Close(Local)")]
public string PlanFinishLocalString
{
get { return PlanFinishLocal?.ToString(); }
}
public DateTime? ActualStartLocal { get; set; }
[DisplayName("Actual Start(Local)")]
public string ActualStartLocalString
{
get { return ActualStartLocal?.ToString(); }
}
public DateTime? ActualFinishLocal { get; set; }
[DisplayName("Actual Close(Local)")]
public string ActualFinishLocalString
{
get { return ActualFinishLocal?.ToString(); }
}
public bool IsGovDirected { get; set; }
public string POC { get; set; }
public string POCPhone { get; set; }
public string WorkOrder { get; set; }
public string ApprovalAuthority { get; set; }
public string AuthorityDocument { get; set; }
public int? FinalVerification { get; set; }
public string FinalVerificationString { get; set; }
public bool WindowActivity { get; set; }
public bool APAC { get; set; }
public DateTime? WAMStartZulu { get; set; }
[DisplayName("WAM Start")]
public string WAMStartZuluString
{
get { return WAMStartZulu?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public DateTime? WAMFinishZulu { get; set; }
[DisplayName("WAM Finish")]
public string WAMFinishZuluString
{
get { return WAMFinishZulu?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public DateTime? AssetAvailable { get; set; }
public string AssetAvailableString
{
get { return AssetAvailable?.ToString(); }
}
[DisplayName("Asset Available")]
public string AssetAvailableStringZulu
{
get { return AssetAvailable?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public DateTime? AssetUnavailable { get; set; }
public string AssetUnavailableString
{
get { return AssetUnavailable?.ToString(); }
}
[DisplayName("Asset Unavailable")]
public string AssetUnavailableStringZulu
{
get { return AssetUnavailable?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public int? AssetStatus { get; set; }
public string AssetStatusString { get; set; }
// renamed to Activity Category
public int? ID_MaintenanceActivity { get; set; }
// renamed to Activity Category
public string ID_MaintenanceActivityString { get; set; }
public string FourtyMinuteNotification { get; set; }
public string Comments { get; set; }
public string QAComments { get; set; }
public bool QACheck { get; set; }
public bool Unscheduled { get; set; }
public string TemplateName { get; set; }
public string SiteName { get; set; }
public bool Environment1 { get; set; }
public bool Environment2 { get; set; }
public bool Environment3 { get; set; }
public string Environments
{
get
{
var envs = "";
if (Environment1)
{
envs += "1";
if (Environment2 || Environment3)
{
envs += ", ";
}
}
if (Environment2)
{
envs += "2";
if (Environment3)
{
envs += ", ";
}
}
if (Environment3)
{
envs += "3";
}
return envs;
}
}
public int? TimeZoneID { get; set; }
public string TimeZone { get; set; }
public int TimeZoneOffset { get; set; }
public string AssetCheck { get; set; }
public string EnvironmentCheck { get; set; }
#endregion
#region ProblemReports
public int ProblemReportID { get; set; }
public string ProblemReportIDString { get; set; }
public int? ProblemReportOwnerID { get; set; }
public int EventID { get; set; }
public string EventString { get; set; }
public int? SubAssembly { get; set; }
public string SubAssemblyString { get; set; }
public DateTime? ActualFailureTime { get; set; }
public string ActualFailureTimeString
{
get { return ActualFailureTime?.ToString(); }
}
[DisplayName("Actual Failure Time")]
public string ActualFailureTimeStringZulu
{
get { return ActualFailureTime?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public DateTime? ActualRestoreTime { get; set; }
public string ActualRestoreTimeString
{
get { return ActualRestoreTime?.ToString(); }
}
[DisplayName("Actual Restore Time")]
public string ActualRestoreTimeStringZulu
{
get { return ActualRestoreTime?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public DateTime? CurrentDateTimeGroup { get; set; }
public string CurrentDateTimeGroupString
{
get { return CurrentDateTimeGroup?.ToString(); }
}
[DisplayName("Current DateTime Group")]
public string CurrentDateTimeGroupStringZulu
{
get { return CurrentDateTimeGroup?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public string FaultEventDescription { get; set; }
public string FaultEventDetails { get; set; }
public string CurrentDayActivities { get; set; }
public string PathForward { get; set; }
public string PartNumber { get; set; }
public DateTime? EstimatedArrivalDate { get; set; }
public string EstimatedArrivalDateString
{
get { return EstimatedArrivalDate?.ToString(); }
}
[DisplayName("Estimated Arrival Date")]
public string EstimatedArrivalDateStringZulu
{
get { return EstimatedArrivalDate?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public string WorkOrderNumber { get; set; }
public string NCR_Number { get; set; }
public string MalfunctionNotes { get; set; }
public string RepairStatus { get; set; }
public DateTime? NextUpdateDue { get; set; }
public string NextUpdateDueString
{
get { return NextUpdateDue?.ToString(); }
}
[DisplayName("Next Update Due")]
public string NextUpdateDueStringZulu
{
get { return NextUpdateDue?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public int OriginatedBy { get; set; }
public string OriginatedByString { get; set; }
public int? ReleasedBy { get; set; }
public string ReleasedByString { get; set; }
public int? ClosedBy { get; set; }
public string ClosedByString { get; set; }
public bool IsClosed { get; set; }
public bool IsNotesVisible { get; set; }
public string TimeStampZuluString
{
get { return TimeStamp.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
[DisplayName("TimeStamp")]
public string TimeStampZuluStringZulu
{
get { return TimeStamp.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public string AssetType { get; set; }
public string AssetSite { get; set; }
public string Rev { get; set; }
public string ETRO { get; set; }
[DisplayName("ETRO")]
public string ETROzulu
{
get
{
if (DateTime.TryParse(ETRO, out DateTime temp))
{
return DateTime.Parse(ETRO).ToString("MM'/'dd'/'yyyy' 'HHmm'z'");
}
else
{
return ETRO;
}
}
}
public string ETROChangeReason { get; set; }
public string NoteArchive { get; set; }
public DAL.ProblemReportDetail currentDetail { get; set; }
public Models.ProblemReportDetails currentDetailModel { get; set; }
[DisplayName("Owner")]
public string ProblemReportOwnerString { get; set; }
public List<Models.ProblemReportDetails> RelatedPRDetails { get; set; }
public string RelatedAssetEnv { get; set; }
#endregion
#region ProblemReportDetails
public int ProblemReportDetailID { get; set; }
public int RevisionID { get; set; }
public bool HasParent { get; set; }
public DateTime? EventDate { get; set; }
public string EventDateString
{
get { return EventDate?.ToString(); }
}
public string EventDateStringZulu
{
get { return EventDate?.ToString("MM'/'dd'/'yyyy' 'HHmm'z'"); }
}
public int ProblemReportTypeID { get; set; }
public string ProblemReportType { get; set; }
public int? MaintenancePriorityID { get; set; }
public string MaintenancePriority { get; set; }
public int MaintenanceStatusID { get; set; }
public string MaintenanceStatus { get; set; }
public int? ParentMaintenanceStatus { get; set; }
public string ParentMaintenanceStatusString { get; set; }
public int DetailRedConID { get; set; }
public string DetailRedConString { get; set; }
public string ETRO_String { get; set; }
public int? ETROChangeReasonID { get; set; }
public string ETROChangeReasonString { get; set; }
#endregion
}
}`
I am looking for the best way to do this... Is it possible to use Union to combine these and return them? I know I could probably convert them all to lists with ToList(), then combine them that way.. What are some ways to do this? I am looking for speed of course, since this will be a lot of data. I figured the ToList() solution would slow things down a bit.
But if the data is unrelated and you just want to combine these collections, you should be able to .Concat() them.
#David is right in that Concat is probably the most straightforward way of doing this. You could add something like this after you do your conversion
var allLogs = allAssetConfigLogs
.Concat(allMissionLogs)
.Concat(allPACLogs)
.Concat(allPRs);
This assumes you want every log in no particular order. If you want distinct logs, you could us Union(), but would need to provide something to compare logs with.
As a side note, I really would recommend something like AutoMapper to handle the conversion of your DB entities to your view model.
Related
Creating Viewmodels and mapping to entities
I am creating ViewModels for my entities. The FirmViewModel contains two list collections called Addressess and Websites. I have also created viewmodels for Addresses and Websites. At the moment in the controller code, I am getting trouble assigning Addresses and Wesbite collections of the Firm Entity to FirmViewModels Addresses and Websites collection. Its says cant cast it implicitly. This is the line in the controller that it complains Addresses = firm.Addresses; How do aassign Systems.Collections.Generic.ICollection<Manager.Model.Address> to Systems.Collections.Generic.ICollection<Manager.WebUI.ViewModels.AddressViewModel> NewFirmViewModel public class NewFirmViewModel { public int FirmId { get; set; } public string FirmName { get; set;} public Nullable<DateTime> DateFounded { get; set; } public ICollection<AddressViewModel> Addresses { get; set; } public ICollection<WebsiteViewModel> Websites { get; set; } public bool hasIntralinks { get; set; } } AddressViewModel public class AddressViewModel { public int AddressId { get; set; } public string Line1 { get; set; } public string Line2 { get; set; } public string Line3 { get; set; } public string Phone { get; set; } public bool IsHeadOffice { get; set; } public int FirmId { get; set; } } WebsiteViewModel public class WebsiteViewModel { private int FirmWebsiteId { get; set; } private string WebsiteUrl { get; set; } public string Username { get; set; } public string Password { get; set; } public int FirmId { get; set; } } Entities - Firm public class FIRM: Entity,IHasAUMs<FIRM_AUM> { public FIRM() { //this.FIRM_PERSON = new HashSet<FIRM_PERSON>(); this.MANAGERSTRATEGies = new HashSet<MANAGERSTRATEGY>(); this.FIRM_ACTIVITY = new HashSet<FIRM_ACTIVITY>(); this.FIRM_AUMs = new HashSet<FIRM_AUM>(); this.FIRM_REGISTRATION = new HashSet<FIRM_REGISTRATION>(); //this.ACTIVITies = new HashSet<ACTIVITY>(); Addresses = new HashSet<ADDRESS>(); //People = new HashSet<PERSON>(); // Websites = new HashSet<FIRM_WEBSITE>(); } //public decimal ID { get; set; } // // // // public string NAME { get; set; } public string SHORT_NAME { get; set; } public string ALTERNATE_NAME { get; set; } public string WEBSITE { get; set; } public string WEBSITE_USERNAME { get; set; } public string WEBSITE_PASSWORD { get; set; } public bool? INTRALINKS_FIRM { get; set; } public string NOTES_TEXT { get; set; } public string NOTES_HTML { get; set; } public string HISTORY_TEXT { get; set; } public string HISTORY_HTML { get; set; } public string HISTORY_SUM_TEXT { get; set; } public string HISTORY_SUM_HTML { get; set; } public Nullable<decimal> OLD_ORG_REF { get; set; } public Nullable<decimal> SOURCE_ID { get; set; } [DisplayFormat(DataFormatString = PermalConstants.DateFormat)] public Nullable<DateTime> DATE_FOUNDED { get; set; } public virtual ICollection<ADDRESS> Addresses { get; set; } // public ICollection<FIRM_WEBSITE> Websites { get; set; } // public ICollection<PERSON> People { get; set; } //public SOURCE SOURCE { get; set; } // public ICollection<FIRM_PERSON> FIRM_PERSON { get; set; } public ICollection<MANAGERSTRATEGY> MANAGERSTRATEGies { get; set; } public ICollection<FIRM_ACTIVITY> FIRM_ACTIVITY { get; set; } public ICollection<FIRM_REGISTRATION> FIRM_REGISTRATION { get; set; } //public ICollection<ACTIVITY> ACTIVITies { get; set; } public ICollection<FIRM_WEBSITE> Websites { get; set; } public Nullable<int> KEY_CONTACT_ID { get; set; } [NotMapped] public ICollection<FIRM_AUM> AUMs { get { return this.FIRM_AUMs; } } public ICollection<FIRM_AUM> FIRM_AUMs { get; set; } } ADDRESS public class ADDRESS : Entity { public ADDRESS() { // DATE_CREATED = DateTime.Now; } public string LINE1 { get; set; } public string LINE2 { get; set; } public string LINE3 { get; set; } public int CITY_ID { get; set; } public string POSTAL_CODE { get; set; } public string SWITCHBOARD_INT { get; set; } public string NOTES { get; set; } public int? OLD_ADDRESS_REF { get; set; } public int? SOURCE_ID { get; set; } public int FIRM_ID { get; set; } [ForeignKey("FIRM_ID")] public FIRM FIRM { get; set; } [ForeignKey("CITY_ID")] public CITY City { get; set; } public ICollection<PERSON> People { get; set; } // public SOURCE SOURCE { get; set; } public bool IS_HEAD_OFFICE { get; set; } [NotMapped] public string AddressBlurb { get { return string.Join(",", new[] { LINE1, LINE2, City != null ? City.NAME : "", City != null && City.Country != null ? City.Country.NAME : "" }.Where(x => !string.IsNullOrEmpty(x))); } } } FIRM_WEBSITE public class FIRM_WEBSITE : Entity { public FIRM_WEBSITE() { } private string _WEBSITE_URL; public string WEBSITE_URL { get { if (string.IsNullOrEmpty(_WEBSITE_URL)) return _WEBSITE_URL; try { var ubuilder = new System.UriBuilder(_WEBSITE_URL ?? ""); return ubuilder.Uri.AbsoluteUri; } catch (UriFormatException ex) { return _WEBSITE_URL; } } set { _WEBSITE_URL = value; } } public string USERNAME { get; set; } public string PASSWORD { get; set; } public int FIRM_ID { get; set; } [ForeignKey("FIRM_ID")] public FIRM FIRM { get; set; } } FirmController public class FirmController : ApiControllerBase { [HttpGet] [Route("api/Firm/{id}")] public IHttpActionResult Details(int id) { var viewModel = GetFirmViewModel(id); return Ok(viewModel); } private NewFirmViewModel GetFirmViewModel(int id) { var firmSvc = GetService<FIRM>(); var firm = firmSvc.GetWithIncludes(id, f => f.Addresses, f => f.Websites); var firmVm = new NewFirmViewModel() { FirmId = firm.ID, FirmName = firm.NAME, DateFounded = firm.DATE_FOUNDED, Addresses = firm.Addresses; }; } public virtual T GetWithIncludes(int id, params Expression<Func<T, object>>[] paths) { try { using (new TimedLogger(_perfLogger, GetCompletedText("GetWithIncludes"), typeof(T).Name)) { return Authorize(_repo.GetWithIncludes(id, paths), AuthAccessLevel.Read); } } catch (Exception ex) { Log(ex); throw; } }
Why is "var update" unreachable code. What Can i do to get multiple returnOk statements working?
Is there a problem for me to use two return Ok statements in one If statement? i am returning Create and update from a class called PardotUtilites and Create returns me an Id. And Update should return first name, email and phone number after editing. namespace GSWebAPI.Controllers { public class CampainProspectsController : ApiController { [HttpPost] public IHttpActionResult Post([FromBody] JToken Value) { string tocreate = ""; //string toupdate = ""; Prospects res = new Prospects(); res.Error = ""; res.Status = ""; var results = JsonConvert.DeserializeObject<Prospects>(Value.ToString()); if (results != null) { // results results.id = Guid.NewGuid().ToString(); tocreate = "first_name=" + results.first_name + "&last_name=" + results.last_name + "&email=" + results.email + "&phone=" + results.phone + "&id=" + results.id; var idstr = PardotUtilities.Create(tocreate); return Ok(idstr); // Error here "unreachable code" var update = PardotUtilities.Update(tocreate, results.id); return Ok(update); PardotUtilities.Upsert(tocreate, results.id); PardotUtilities.Query(tocreate, results.id); PardotUtilities.Delete(tocreate, results.id); // return Ok(update); } return Ok(); } //public class public class Prospects { public String Status { get; set; } public String Error { get; set; } public string id { get; set; } public string email { get; set; } public string first_name { get; set; } public string last_name { get; set; } public string password { get; set; } public string company { get; set; } public string website { get; set; } public string job_title { get; set; } public string department { get; set; } public string contry { get; set; } public string address_one { get; set; } public string address_two { get; set; } public string city { get; set; } public string state { get; set; } public string territory { get; set; } public string zip { get; set; } public string phone { get; set; } public string fax { get; set; } public string source { get; set; } public string annual_revenue { get; set; } public string employees { get; set; } public string industry { get; set; } public string years_in_business { get; set; } public string comments { get; set; } public string notes { get; set; } public string score { get; set; } public string grade { get; set; } public string last_activity_at { get; set; } public string recent_interaction { get; set; } public string crm_lead_fid { get; set; } public string crm_contact_fid { get; set; } public string crm_owner_fid { get; set; } public string crm_account_fid { get; set; } public string salesforce { get; set; } public string crm_last_sync { get; set; } public string crm_url { get; set; } public string is_do_not_email { get; set; } public string is_do_not_call { get; set; } public string opted_out { get; set; } public string is_reviewed { get; set; } public string is_starred { get; set; } public string created_at { get; set; } public string updated_at { get; set; }
When the method reaches return Ok(idstr); The code resumes where the method was called and therefore never reaches return Ok(update);
Reading from Xml FIle into existing dataTable C# ASP.NET Core
Here is the method where I have the problem: [HttpPost] public async Task<IActionResult> XmlPage(IFormFile xmlFile) { var uploads = hostingEnvironment.WebRootPath; if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml")) { try { using (var fileStream = new FileStream(Path.Combine(uploads, xmlFile.FileName), FileMode.Create)) { await xmlFile.CopyToAsync(fileStream); XDocument xDoc = XDocument.Load(fileStream); List<DmgRegister> dmgRegistterList = xDoc.Descendants("Claim").Select(dmgReg => new DmgRegister { Uwyear = dmgReg.Element("UWYear").Value, ClaimNo = dmgReg.Element("ClaimNo").Value, PolicyNo = dmgReg.Element("PolicyNo").Value, PolicyName = dmgReg.Element("PolicyHolder").Value, Address1 = dmgReg.Element("Address1").Value, Address2 = dmgReg.Element("Addresstype").Value, PostalLocation = dmgReg.Element("City").Value, Country = dmgReg.Element("Country").Value, PostalCode = dmgReg.Element("Postalzone").Value }).ToList(); context.SaveXmlToDb(dmgRegistterList); } catch { //Here where i come when i try to upload and parse the data ViewBag.Error = "Converting fail"; return View("Export"); } } else { ViewBag.Error = "Uploading fail"; return View("Index"); } return View(); } Im trying to upload an xml file and then parse into a SQL Table(Sql DataTable named DmgRegister), I'm a beginner with ASP.Net so exuse me if the code looks like an italian spaghetti. // SaveXmlToDb method in context foreach (var item in dmgRegistterList) { DmgRegister.Add(item); } SaveChanges(); } Now the Model that I'm trying to bind data from XML and save it to DataTable [Serializable] [XmlRoot("Claims")] public class Claim { [XmlElement("ClientName")] public string ClientName { get; set; } [XmlElement("UWYear")] public string Uwyear { get; set; } [XmlElement("AgreementNo")] public string AgreementNo { get; set; } [XmlElement("BusinessType")] public string BusinessType { get; set; } [XmlElement("PeriodStart")] public DateTime? PeriodStart { get; set; } [XmlElement("PeriodEnd")] public DateTime? PeriodEnd { get; set; } [XmlElement("PolicyNo")] public string PolicyNo { get; set; } [XmlElement("PolicyHolder")] public string PolicyName { get; set; } [XmlElement("DateOfLoss")] public DateTime? DateOfLoss { get; set; } [XmlElement("ClaimNo")] public string ClaimNo { get; set; } [XmlElement("ClaimantName")] public string ClaimantName { get; set; } [XmlElement("ClaimedInsured")] public string ClaimedInsured { get; set; } [XmlElement("ReportDate")] public DateTime? ReportDate { get; set; } [XmlElement("CountryOfRisk")] public string CountryOfRisk { get; set; } [XmlElement("CountryOfLoss")] public string CountryOfLoss { get; set; } [XmlElement("TypeOfLoss")] public string TypeOfLoss { get; set; } [XmlElement("InsuranceCoverage")] public string InsuranceCoverage { get; set; } [XmlElement("LineOfBuisnessNo")] public int? LineOfBuisnessNo { get; set; } [XmlElement("LineOfBuisnessName")] public string LineOfBuisnessName { get; set; } [XmlElement("ClassOfBuisnessNo")] public int? ClassOfBuisnessNo { get; set; } [XmlElement("ClassOfBuisnessName")] public string ClassOfBuisnessName { get; set; } [XmlElement("CaptiveShare")] public int? CaptiveShare { get; set; } [XmlElement("OriginalCurrency")] public string OriginalCurrency { get; set; } [XmlElement("PaymentCurrency")] public string PaidInCurrency { get; set; } [XmlElement("TotalIncurredCaptiveShare")] public decimal? TotalIncurredCaptiveShare { get; set; } [XmlElement("PaidThisPeriod")] public decimal? PaidThisPeriod { get; set; } [XmlElement("PeriodDate")] public DateTime? PeriodDate { get; set; } [XmlElement("PaymentDate")] public DateTime? PaymentDate { get; set; } [XmlElement("TotalPaidCaptiveShare")] public decimal? TotalPaidCaptiveShare { get; set; } [XmlElement("RemainingReserveCaptiveShare")] public decimal? RemainingReserveCaptiveShare { get; set; } [XmlElement("Deductible")] public string Deductible { get; set; } [XmlElement("Recovery")] public string Recovery { get; set; } [XmlElement("LocationAdress")] public string LocationAdress { get; set; } [XmlElement("Address1")] public string Address1 { get; set; } [XmlElement("Addresstype")] public string Address2 { get; set; } [XmlElement("Postalzone")] public string PostalCode { get; set; } [XmlElement("City")] public string PostalLocation { get; set; } [XmlElement("Country")] public string Country { get; set; } [XmlElement("GeograficalDiversification")] public string GeograficalDiversification { get; set; } [XmlElement("Cause")] public string Cause { get; set; } [XmlElement("Status")] public string Status { get; set; } [XmlElement("CloseDate")] public DateTime? CloseDate { get; set; } [XmlElement("DevelopmentYear")] public string DevelopmentYear { get; set; } [XmlElement("TotalIncurredInsurerShare")] public decimal? TotalIncurredInsurerShare { get; set; } [XmlElement("TotalPaidInsurerShare")] public decimal? TotalPaidInsurerShare { get; set; } [XmlElement("RemainingReserveInsurerShare")] public decimal? RemainingReserveInsurerShare { get; set; } } [Serializable()] [XmlRoot("Claims")] public class Claims { [XmlArray("Claims")] [XmlArrayItem("Claim", typeof(Claim))] public Claim[] Claim { get; set; } } Here is the Xml example that im try upload <ns0:Claims> <Claim> <ClaimNo>LL0000110262</ClaimNo> <PolicyNo>LP0000004481</PolicyNo> <PolicyHolder>NCC Rakennus Oy</PolicyHolder> <AddressId>1</AddressId> <Address1>Example Street 1</Address1> <Addresstype>LocationOfLoss</Addresstype> <City>Helsinki</City> <Country>FI</Country> <Postalzone>12345</Postalzone> <UWYear>2015</UWYear> <PeriodStart>2015-01-01</PeriodStart> <PeriodEnd>2015-12-31</PeriodEnd> <DateOfLoss>2015-07-15</DateOfLoss> <ReportDate/> <StatusAsPer>2015-12-31</StatusAsPer> <Coverage>?</Coverage> <TypeOfLoss>Leakage</TypeOfLoss> <OriginalCurrency>EUR</OriginalCurrency> <PaymentCurrency>EUR</PaymentCurrency> <TotalReservesOrigCurr>0.00</TotalReservesOrigCurr> <TotalPaymentOrigCurr>0.00</TotalPaymentOrigCurr> <DeductibleOrigCurr>85000.00</DeductibleOrigCurr> <TotalAmountOfClaimOrigCurr>3680.00</TotalAmountOfClaimOrigCurr> <Status>Active</Status> </Claim> </ns0:Claims> I try it even to convert from XML to JSON, but it jumps to catch public async Task<IActionResult> XmlPage(IFormFile xmlFile) { var uploads = hostingEnvironment.WebRootPath; var filePath = Path.Combine(uploads, xmlFile.FileName); if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml")) { try { using (var xReader = XmlReader.Create(new StringReader(filePath))) { // This line skips the XML declaration, eg "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" - you can skip this if you don't have declaration as in your case xReader.MoveToContent(); // Gets the actual XMLElement, if any xReader.Read(); // Convert the xReader to an XNode for the Json serializer XNode node = XNode.ReadFrom(xReader); // Json output string jsonText = JsonConvert.SerializeXNode(node); } } catch { ViewBag.Error = "Converting fail"; return View("Export"); } } else { ViewBag.Error = "Uploading fail"; return View(); } return View("Index"); }
Thx a lot CountZero, really gratefull after my first question here, still had issues but now is everything working, The method in controller public async Task<IActionResult> XmlPage(IFormFile xmlFile) { var uploads = hostingEnvironment.WebRootPath; var filePath = Path.Combine(uploads, xmlFile.FileName).ToString(); if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml")) { try { using (var fileStream = new FileStream(filePath, FileMode.Create)) { await xmlFile.CopyToAsync(fileStream); fileStream.Dispose(); XDocument xDoc = XDocument.Load(filePath); List<DmgRegisterVM> dmgRegistterList = xDoc.Descendants("Claim").Select(dmgReg => new DmgRegisterVM { Uwyear = dmgReg.Element("UWYear").Value, ClaimNo = dmgReg.Element("ClaimNo").Value, PolicyNo = dmgReg.Element("PolicyNo").Value, PolicyName = dmgReg.Element("PolicyHolder").Value, Address1 = dmgReg.Element("Address1").Value, Address2 = dmgReg.Element("Addresstype").Value, PostalLocation = dmgReg.Element("City").Value, Country = dmgReg.Element("Country").Value, PostalCode = dmgReg.Element("Postalzone").Value }).ToList(); context.SaveXmlToDb(dmgRegistterList); } } catch(Exception e) { ViewBag.Error = "Converting fail"; } } else { ViewBag.Error = "Uploading fail"; } return View("Index"); } SaveXmlToDb method in context public void SaveXmlToDb(List<DmgRegisterVM> dmgRegList) { //from list to database foreach (var item in dmgRegList) { var model = Mapper.Map<DmgRegister>(item); DmgRegister.Add(model); SaveChanges(); } } And finally the Claim class (where i have XML elements) [Serializable] [XmlRoot("ns0:Claims")] public class Claim { [XmlElement("ClientName")] public string ClientName { get; set; } [XmlElement("UWYear")] public string Uwyear { get; set; } [XmlElement("AgreementNo")] public string AgreementNo { get; set; } [XmlElement("BusinessType")] public string BusinessType { get; set; } [XmlElement("PeriodStart")] public DateTime? PeriodStart { get; set; } [XmlElement("PeriodEnd")] public DateTime? PeriodEnd { get; set; } [XmlElement("PolicyNo")] public string PolicyNo { get; set; } [XmlElement("PolicyHolder")] public string PolicyName { get; set; } [XmlElement("DateOfLoss")] public DateTime? DateOfLoss { get; set; } [XmlElement("ClaimNo")] public string ClaimNo { get; set; } [XmlElement("ClaimantName")] public string ClaimantName { get; set; } [XmlElement("ClaimedInsured")] public string ClaimedInsured { get; set; } [XmlElement("ReportDate")] public DateTime? ReportDate { get; set; } [XmlElement("CountryOfRisk")] public string CountryOfRisk { get; set; } [XmlElement("CountryOfLoss")] public string CountryOfLoss { get; set; } [XmlElement("TypeOfLoss")] public string TypeOfLoss { get; set; } [XmlElement("InsuranceCoverage")] public string InsuranceCoverage { get; set; } [XmlElement("LineOfBuisnessNo")] public int? LineOfBuisnessNo { get; set; } [XmlElement("LineOfBuisnessName")] public string LineOfBuisnessName { get; set; } [XmlElement("ClassOfBuisnessNo")] public int? ClassOfBuisnessNo { get; set; } [XmlElement("ClassOfBuisnessName")] public string ClassOfBuisnessName { get; set; } [XmlElement("CaptiveShare")] public int? CaptiveShare { get; set; } [XmlElement("OriginalCurrency")] public string OriginalCurrency { get; set; } [XmlElement("PaymentCurrency")] public string PaidInCurrency { get; set; } [XmlElement("TotalIncurredCaptiveShare")] public decimal? TotalIncurredCaptiveShare { get; set; } [XmlElement("PaidThisPeriod")] public decimal? PaidThisPeriod { get; set; } [XmlElement("PeriodDate")] public DateTime? PeriodDate { get; set; } [XmlElement("PaymentDate")] public DateTime? PaymentDate { get; set; } [XmlElement("TotalPaidCaptiveShare")] public decimal? TotalPaidCaptiveShare { get; set; } [XmlElement("RemainingReserveCaptiveShare")] public decimal? RemainingReserveCaptiveShare { get; set; } [XmlElement("Deductible")] public string Deductible { get; set; } [XmlElement("Recovery")] public string Recovery { get; set; } [XmlElement("LocationAdress")] public string LocationAdress { get; set; } [XmlElement("Address1")] public string Address1 { get; set; } [XmlElement("Addresstype")] public string Address2 { get; set; } [XmlElement("Postalzone")] public string PostalCode { get; set; } [XmlElement("City")] public string PostalLocation { get; set; } [XmlElement("Country")] public string Country { get; set; } [XmlElement("GeograficalDiversification")] public string GeograficalDiversification { get; set; } [XmlElement("Cause")] public string Cause { get; set; } [XmlElement("Status")] public string Status { get; set; } [XmlElement("CloseDate")] public DateTime? CloseDate { get; set; } [XmlElement("DevelopmentYear")] public string DevelopmentYear { get; set; } [XmlElement("TotalIncurredInsurerShare")] public decimal? TotalIncurredInsurerShare { get; set; } [XmlElement("TotalPaidInsurerShare")] public decimal? TotalPaidInsurerShare { get; set; } [XmlElement("RemainingReserveInsurerShare")] public decimal? RemainingReserveInsurerShare { get; set; } } //[ModelMetadataType(typeof(DmgRegisterMetaData))] [Serializable()] [XmlRoot("ns0:Claims")] public class ClaimsCollection { [XmlArray("Claims")] [XmlArrayItem("Claim", typeof(Claim))] public Claim[] Claim { get; set; } }
Given you are getting a "Root element is missing" this looks like an issue with your mapping. [XmlRoot("Claims")] will not map onto <ns0:Claims>. Try updating your XML so the roots element is set to <Claims></Claims> rather than <ns0:Claims></ns0:Claims>. If this fixes it then you can either change your XML or update your attribute in the class so it looks like this. [XmlRoot("ns0:Claims")].
Combine to lists of same type but less fields in each
I am trying to cobine three lists that will always return certain properties out of a list of assets i need to combine these three lists into one list. But not all fields of the master list is filled in List<Asset> allAssets = new List<Asset>(); List<Asset> _vheiclesList = new List<Asset>(); _vheiclesList = getallVechiclesForSlate(); List<Asset> _propertyList = new List<Asset>(); _vheiclesList = getAllPropertyForSlate(); var AllAssets = allAssets.Concat(_vheiclesList) .Concat(_propertyList) .ToList(); _createCase.Assets = AllAssets; But i am getting a nullable object must have a value and I dont no why. public List<Asset> getAllPropertyForSlate() { try { List<tbl_Property> _property = new List<tbl_Property>(); Asset _asset = new Asset(); _property = dal.GetPropertiesById(caseid); foreach (var property in _property) { _asset.Id = Guid.NewGuid(); _asset.AssetType =(int) slateExportsConstants.AsssetTypes.Property; _asset.Description = property.addressLine1 + " " + property.addressLine2 + property.county + " " + property.country + " " + property.postCode; _asset.CurrentValue =(int) Math.Round(Convert.ToDecimal(property.valueOfProperty.Value)); string valuationDateIso = JsonConvert.SerializeObject(property.dateofValuation.Value); _asset.ValuationDate = valuationDateIso; if (property.thirdPartyOwner == new Guid(fhsConstants.fhsPartner)) { _asset.Owner = (int)slateExportsConstants.Applicant.Applicant2; } else if (property.thirdPartyOwner == new Guid(fhsConstants.fhsExPartner)) { _asset.Owner = (int)slateExportsConstants.Applicant.Joint; } if(property.isHomeAddress==true) { _asset.Home =(bool) property.isHomeAddress; } if (property.housingAssoication == true) { _asset.HousingAssociation = property.housingAssoicationShare.ToString(); } if (property.isHomeAddress == true) { _asset.Home = true; } _asset.Equity = Convert.ToInt32(property.valueOfEquity); _asset.IsSharedOwnership = property.coOwnerdByAnyOtherParty; _assets.Add(_asset); } return _assets; } catch(Exception ex) { return null; } } public class Asset { public Guid Id { get; set; } public string Description { get; set; } public int CurrentValue { get; set; } public string ValuationDate { get; set; } public int Owner { get; set; } public int OutstandingFinance { get; set; } public int FinanceAccountHolder { get; set; } public int FinanceMonthlyPayment { get; set; } public DateTime FinanceEndDate { get; set; } public bool Home { get; set; } public int AssetType { get; set; } public DateTime FixedPeriodEndDate { get; set; } public int ValuationSource { get; set; } public int Equity { get; set; } public bool IsSharedOwnership { get; set; } public string HousingAssociation { get; set; } public int HousingAssociationShareOfPropertyPercent { get; set; } public bool BeneficialInterest { get; set; } public int JointOwner1 { get; set; } public int JointOwner2 { get; set; } public string JointOwner3 { get; set; } public int RentalIncome { get; set; } public string AccountNumber { get; set; } public string PropertySecuredAgainstId { get; set; } public string FinanceCompany { get; set; } }
Is it because of the line: _vheiclesList = getAllPropertyForSlate(); Should it read: _propertyList = getAllPropertyForSlate();
JSON Serializer C#
I am developing online aircraft sales system. But I have a problem.. A URL address have: string urlFlightSearch = "https://api.iati.com/rest/flightSearch/" + ado.iatiKod + ""; A have class "iati.cs" in codes public class iati { public class flightSearch { public string fromAirport { get; set; } public bool allinFromCity { get; set; } public string toAirport { get; set; } public string fromDate { get; set; } public string returnDate { get; set; } public string adult { get; set; } public string currency { get; set; } } public class Leg { public string flightNo { get; set; } public string aircraft { get; set; } public string operatorCode { get; set; } public string operatorName { get; set; } public string departureAirport { get; set; } public string departureTime { get; set; } public string departureAirportName { get; set; } public string departureCityName { get; set; } public string arrivalAirport { get; set; } public string arrivalTime { get; set; } public string arrivalAirportName { get; set; } public string arrivalCityName { get; set; } } public class Detail { public double price { get; set; } public double serviceFee { get; set; } public double tax { get; set; } public int suplement { get; set; } } public class Fare { public double totalSingleAdultFare { get; set; } public string currency { get; set; } public string type { get; set; } public List<string> segmentNames { get; set; } public int freeSeatCount { get; set; } public Detail detail { get; set; } } public class Flight { public string id { get; set; } public string providerKey { get; set; } public string pricingType { get; set; } public int packageId { get; set; } public List<Leg> legs { get; set; } public List<Fare> fares { get; set; } public int segmentCount { get; set; } public int baggage { get; set; } public int flightTimeHour { get; set; } public int flightTimeMinute { get; set; } public int layoverTime { get; set; } public bool hasCip { get; set; } public bool canBook { get; set; } public bool canRezerve { get; set; } public bool dayCross { get; set; } public bool returnFlight { get; set; } } public class Result { public string searchId { get; set; } public List<Flight> flights { get; set; } } public class RootObject { public Result result { get; set; } } } And posting... WebClient wc = new WebClient(); var serializer = new JavaScriptSerializer(); iati.flightSearch search = new iati.flightSearch() { fromAirport = "IST", allinFromCity = true, toAirport = "AYT", fromDate = "2013-12-23", returnDate = "2013-12-30", adult = "1", currency = "EUR" }; var serializedResult = serializer.Serialize(search); wc.Headers[HttpRequestHeader.ContentType] = "application/json"; string result = wc.UploadString(urlFlightSearch, serializedResult); iati.Flight flight = serializer.Deserialize<iati.Flight>(result); But the result returned is always coming up empty. Regards.
use Newtonsoft JsonConvert.DeserializeObject(result);