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.
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; }
}
I want to know which one performs faster
from JsonConvert.DeserializeObject or Custom model binding
for Example:
My ViewModel class:
public class AssessmentViewModel : BaseViewModel
{
public Guid AssessmentGUID { get; set; }
public string AssessmentCategory { get; set; }
public string AssessmentType { get; set; }
public string AssessmentName { get; set; }
public string AssessmentNameEnglish { get; set; }
public string AssessmentInstruction { get; set; }
public string AssessmentInstructionEnglish { get; set; }
public int? SequenceNum { get; set; }
public int? MaxScore { get; set; }
public bool? IsNegativeMarking { get; set; }
public decimal? NegativeRatio { get; set; }
public List<StringMapDDLViewModel> AssessmentCategoryDDList { get; set; }
public List<StringMapDDLViewModel> AssessmentTypeDDList { get; set; }
public List<FOFormSectionViewModel> FOFormSectionList { get; set; }
public List<StringMapDDLViewModel> FieldTypeList { get; set; }
public List<StringMapDDLViewModel> ValidationTypeList { get; set; }
}
I am calling Stored Procedure and it returns 100 thousands of data.
So my question is which will perform faster from below code:
Method 1: Serialize result then Deserialize it.
var assessmentList = db.AssessmentSP(Constant.ActionGetAll, null, status).ToList<AssessmentSP_Result>();
objALVM.AssessmentList = JsonConvert.DeserializeObject<List<AssessmentViewModel>>(JsonConvert.SerializeObject(assessmentList));
Method 2: One by one property binding
var assessmentList = db.AssessmentSP(Constant.ActionGetAll, null, status).ToList<AssessmentSP_Result>().ToList();
objALVM.AssessmentList = assessmentList.Select(x => new AssessmentViewModel()
{
AssessmentGUID = x.AssessmentGUID,
AssessmentType = x.AssessmentType,
AssessmentName = x.AssessmentName,
AssessmentNameEnglish = x.AssessmentNameEnglish,
AssessmentInstruction = x.AssessmentInstruction,
AssessmentInstructionEnglish = x.AssessmentInstructionEnglish,
SequenceNum = x.SequenceNum,
MaxScore = x.MaxScore,
IsNegativeMarking = x.IsNegativeMarking,
NegativeRatio = x.NegativeRatio,
}).ToList();
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();
public static List<IndianAppStore_GetAllAppsByLanguage_ResultCache> GetAllApps(bool initialized, string language)
{
List<IndianAppStore_GetAllAppsByLanguage_ResultCache> objApp = new List<IndianAppStore_GetAllAppsByLanguage_ResultCache>();
List<IndianAppStore_GetAllAppsByLanguage_Result> objApps = new List<IndianAppStore_GetAllAppsByLanguage_Result>();
if (initialized == false)
{
var t = ListCopy(objApps, x => (IndianAppStore_GetAllAppsByLanguage_ResultCache)x); // Error
objApp = admin.getAllAppsByLanguage(language).ToList();
}
else
{
}
}
public static List<TResult> ListCopy<TSource, TResult>(List<TSource> input, Func<TSource, TResult> convertFunction)
{
return input.Select(x => convertFunction(x)).ToList();
}
My Class
public class IndianAppStore_GetAllAppsByLanguage_ResultCache
{
public long AppId { get; set; }
public string AppName { get; set; }
public string AppDisplayName { get; set; }
public string AppDetails { get; set; }
public string AppImageURL { get; set; }
public byte[] AppImageData { get; set; }
public long CategoryId { get; set; }
public Nullable<long> SubCategoryId { get; set; }
public string AppCreatedBy { get; set; }
public System.DateTime AppCreatedOn { get; set; }
public string AppModifiedBy { get; set; }
public Nullable<System.DateTime> AppModifiedOn { get; set; }
public Nullable<bool> isDeleted { get; set; }
public Nullable<bool> isPromotional { get; set; }
public string GenderTarget { get; set; }
public Nullable<long> CountryId { get; set; }
public Nullable<long> StateId { get; set; }
public Nullable<long> AgeLimitId { get; set; }
public Nullable<int> AppMinAge { get; set; }
public Nullable<int> AppMaxAge { get; set; }
}
I am trying to convert one generic class to another but getting this error
IndianAppStore_GetAllAppsByLanguage_Result and IndianAppStore_GetAllAppsByLanguage_ResultCache are different types and you cannot cast the first type to the other as you are doing in this statement:
var t = ListCopy(objApps, x => (IndianAppStore_GetAllAppsByLanguage_ResultCache)x);
If the types have the same structure you should probably just have one instead of two types. Otherwise you will have to copy the data from the first type to the other. E.g.:
var t = ListCopy(objApps, x => new IndianAppStore_GetAllAppsByLanguage_ResultCache {
AppId = x.AppId,
AppName = x.AppName,
...
});
This becomes tedious very quickly and one option is to use a library like AutoMapper to automate the process.