Creating Viewmodels and mapping to entities - c#

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

Related

What is the best way to combine multiple DbQuery results?

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.

E.F Core does not return all values When Include another table

public IEnumerable<Parties> GetAll()
{
return database.Parties;
}
Works very well and the output is:
But when I Include another table by foreignkey like this:
public IEnumerable<Parties> GetAll()
{
return database.Parties.Include(i=>i.User);
}
It does not work, it returns first value of the table and nothing else,the output is :
Users.cs :
public partial class Users
{
public Users()
{
Parties = new HashSet<Parties>();
PartyParticipants = new HashSet<PartyParticipants>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Avatar { get; set; }
public string Biography { get; set; }
public string Password { get; set; }
public virtual ICollection<Parties> Parties { get; set; }
public virtual ICollection<PartyParticipants> PartyParticipants { get; set; }
}
Parties.cs :
public partial class Parties
{
public Parties()
{
Image = new HashSet<Image>();
PartyParticipants = new HashSet<PartyParticipants>();
}
public int Id { get; set; }
public string Name { get; set; }
public DateTime PartyDate { get; set; }
public DateTime CreatedDate { get; set; }
public int ParticipantCount { get; set; }
public int MaxParticipant { get; set; }
public string PartySplash { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public bool EntranceFree { get; set; }
public int? FreeParticipant { get; set; }
public int? FreeParticipantMax { get; set; }
public int UserId { get; set; }
public virtual Users User { get; set; }
public virtual ICollection<Image> Image { get; set; }
public virtual ICollection<PartyParticipants> PartyParticipants { get; set; }
}
As you can see on the 2nd picture it interrupts at first row of the table.
I have added this answer based on Vidmantas's comment. ReferenceLoopHandling should be ignored like this in startup.cs:
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});

Disable Lazy Load EF6 DBFirst at .NET Framework

In my webapi2 application I used db first generation and I created a partial class of context to set both ProxyCreationEnabledand LazyLoadingEnabled to false.
But when I use db.ExameViaAereaOssea.Where(e => e.ConsultaId == model.ConsultaId).ToList() the relation property Consulta is loaded too.
That not happing when I use db.ExameViaAereaOssea.AsNoTracking().Where(e => e.ConsultaId == consultaId).ToList()
I don't want use AsNoTracking for every query
Here are my two classes
public partial class ExameViaAereaOssea
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ExameViaAereaOssea()
{
}
public int ExameViaAereaOsseaId { get; set; }
public Nullable<int> ConsultaId { get; set; }
public string VAOE125 { get; set; }
public string VAOE250 { get; set; }
public string VAOE500 { get; set; }
public string VAOE750 { get; set; }
public string VAOE1000 { get; set; }
public string VAOE1500 { get; set; }
public string VAOE2000 { get; set; }
public string VAOE3000 { get; set; }
public string VAOE4000 { get; set; }
public string VAOE6000 { get; set; }
public string VAOE8000 { get; set; }
public string VOOE500 { get; set; }
public string VOOE750 { get; set; }
public string VOOE1000 { get; set; }
public string VOOE2000 { get; set; }
public string VOOE3000 { get; set; }
public string VOOE4000 { get; set; }
public string TipoAudiometria { get; set; }
public virtual Consulta Consulta { get; set; }
}
public partial class Consulta
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Consulta()
{
this.ExameViaAereaOssea = new HashSet<ExameViaAereaOssea>();
}
public int ConsultaId { get; set; }
public DateTime? Data {get;set;}
public Nullable<int> PacienteId { get; set; }
public Nullable<int> TipoConsultaId { get; set; }
public Nullable<int> PacienteDadosProfissionaisId { get; set; }
public Nullable<int> ClienteId { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ExameViaAereaOssea> ExameViaAereaOssea { get; set; }
}
And here is the usage.
public class RegraConsulta(){
public ExamesConsulta BuscaExamesConsulta(Consulta model) {
using (var db = new winmedEntities(false))
{
var retorno = new ExamesConsulta();
retorno.DataConsulta = RetornaDataConsulta(db, model.ConsultaId);
retorno.exAereaOssea = db.ExameViaAereaOssea.Where(c => c.ConsultaId == model.ConsultaId).ToList();
return retorno;
}
}
public DateTime RetornaDataConsulta(winmedEntities db, int consultaId)
{
var consulta = db.Consulta.Find(consultaId);
if (consulta == null)
throw new RegraNegocioException("Consulta não encontrada");
return consulta.Data.Value;
}
}
The return is used in Web Api Controller and return method used like return Ok(new RegraConsulta().BuscaExamesConsulta(new Consulta { ConsultaId = 1 }));

Strip all values from C# objects using Reflection

I have the following method which is used to retrieve all values as strings from an object using reflection. The object can have IEnumerables within them and I also want to retrieve these values. A list of ignore fields also needs to be taken into account so that those field's values are not returned.
public static IEnumerable<string> StringContent(this object obj, IEnumerable<string> ignoreProperties = null)
{
Type t = obj.GetType();
foreach (var prop in t.GetProperties())
{
if (ignoreProperties != null && ignoreProperties.Contains(field.Name))
{
continue;
}
var value = prop.GetValue(obj);
if (value != null)
{
if (value is IEnumerable<object>)
{
foreach (var item in (IEnumerable<object>)value)
{
foreach (var subValue in item.StringContent())
{
yield return subValue.ToString();
}
}
}
else
{
yield return value.ToString();
}
}
}
}
This method does work perfectly and gives me the correct result. However, I need to speed it up as much as possible because this is performed a lot of times.
Does anybody have any suggestions?
Thanks in advance!
** EDIT **
Example Test Case:
[TestMethod]
public void StringContent()
{
Project project = projectA;
List<string> ignoreFields = new List<string>() { "SalesEngineer", "CreationDate" };
var result = project.StringContent(ignoreFields);
Assert.IsTrue(result.Count() == 26);
}
Project Object:
public class Project : IEntity
{
public Project()
{
Products = new List<ProjectProducts>();
}
public int Id { get; set; }
public DateTime CreationDate { get; set; }
public string SalesEngineer { get; set; }
public string SalesEngineerEmail { get; set; }
public int? TeamId { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Originator { get; set; }
public string ContactName { get; set; }
public string MainClient { get; set; }
public string Contractor { get; set; }
public string ContractorContactName { get; set; }
public string ContractorLocation { get; set; }
public string Wholesaler { get; set; }
public string WholesalerContactName { get; set; }
public string WholesalerLocation { get; set; }
public float EstimatedValue { get; set; }
public float CalculatedValue {
get { return EstimatedValue/Convert.ToSingle(Currency != null ? Currency.Rate : (decimal)1.0); }
}
public int Probability { get; set; }
public int SectorId { get; set; }
public int TypeId { get; set; }
public string StatusCode { get; set; }
public string LostTo { get; set; }
public int ReasonId { get; set; }
public string SecondaryEngineer { get; set; }
public float SplitPercentage { get; set; }
public DateTime ExpectedOrder { get; set; }
public DateTime? RequiredOnSiteBy { get; set; }
public bool LightingDesignRequired { get; set; }
public string ReasonForLightingDesign { get; set; }
public DateTime? DesignRequiredBy { get; set; }
public DateTime? FollowUp { get; set; }
public string Comments { get; set; }
public int CurrencyId { get; set; }
public bool Void { get; set; }
public string AttachmentFolder { get; set; }
public virtual Currency Currency { get; set; }
public virtual Reason Reason { get; set; }
public virtual ProjectStatus Status { get; set; }
public virtual ProjectType Type { get; set; }
public virtual Sector Sector { get; set; }
public virtual ICollection<ProjectProducts> Products { get; set; }
public virtual Team Team { get; set; }
public object Key
{
get { return Id; }
}
}
You can use stringify package.
It exists in Nuget.
You can Hide parameters with Hidden attribute.
You can print every object with a.stringify();

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

Categories

Resources