Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Query: incorrectly generating JOIN rather than APPLY for subqueries with outside references to a joined table #19825

Closed
yahorsi opened this issue Feb 7, 2020 · 14 comments · Fixed by #20008
Assignees
Labels
area-query closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported Servicing-approved type-bug
Milestone

Comments

@yahorsi
Copy link

yahorsi commented Feb 7, 2020

Hi Guys,

We just migrated to the latest EF 3.1.1 and it seems at least in 1 case EF generates invalid SQL query.
Instead of generating outer apply EF generates invalid left join. I'm posting the code as-is, extracting it into the small runnable project will take time.
So, here is the query:

            var query =
                from r in Context.Rotations
                join rd in Context.RotationDuties on r.Id equals rd.RotationId
                join f in Context.Flights on rd.FlightId equals f.Id
                join d in Context.Duties on f.Id equals d.FlightId
                join p in Context.Persons on d.PersonId equals p.Id
                join a in Context.Activities on d.ActivityId equals a.Id

                join pd in Context.PersonDays on new { d.PersonId, d.Date } equals new { pd.PersonId, pd.Date } into pdJoin
                from pd in pdJoin.DefaultIfEmpty()

                from pe in Context.PersonExperiences.Where(pe => pe.DateFrom <= rd.Date && (rd.Date <= pe.DateTo || pe.DateTo == null) && pe.PersonId == d.PersonId).DefaultIfEmpty()
                join e in Context.Experiences on pe.ExperienceId equals e.Id into eJoin
                from e in eJoin.DefaultIfEmpty()

                join pf in Context.PersonFunctions.Where(pf => pf.DateFrom <= date && (pf.DateTo == null || pf.DateTo > date)) on p.Id equals pf.PersonId into pfGroup
                from pf in pfGroup.DefaultIfEmpty()

                join func in Context.Functions on pf.FunctionId equals func.Id into funcGroup
                from func in funcGroup.DefaultIfEmpty()

                where r.Id == id

                select new RotationDutyActivity
                {
                    Date = d.Date,
                    PersonId = d.PersonId,
                    PersonCodeName = p.Code,
                    ActivityCodeName = a.CodeName,
                    FlightId = f.Id,
                    FlightNumber = f.FlightNumber,

                    FlightDepartureDateTimeUtc = f.DepartureDateTimeUtc,

                    PersonExperienceCodeName = e == null ? null : e.CodeName,
                    PersonBirthDate = p.BirthDate,
                    FlightIsAugmentedCockpit = f.IsAugmentedCockpit,
                    FlightIsExtendedCockpit = f.IsExtendedCockpit,
                    FlightIsAugmentedCabin = f.IsAugmentedCabin,
                    FlightIsExtendedCabin = f.IsExtendedCabin,
                    FunctionName = func == null ? null : func.Name,

                    HasFtlErrors = pd == null ? false : pd.HasFtlErrors,
                    HasGavErrors = pd == null ? false : pd.HasGavErrors,
                    HasEasaErrors = pd == null ? false : pd.HasEasaErrors,
                    HasAgreementErrors = pd == null ? false : pd.HasAgreementErrors,
                    HasOtherErrors = pd == null ? false : pd.HasOtherErrors
                };

And the exception is:

The multi-part identifier "r0.Date" could not be bound.
   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
   at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
   at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()

And SQL generated is the following (obtained using Diagnostics Source):

DECLARE @__IsHistorized_0 Bit = 0;
DECLARE @__date_1 Date = '2019-12-08T00:00:00';
DECLARE @__date_2 Date = '2019-12-08T00:00:00';
DECLARE @__id_3 UniqueIdentifier = '57080c13-5a4b-0000-0002-070000000000';


SELECT [t].[Date], [t].[PersonId], [p].[Code] AS [PersonCodeName], [a].[CodeName] AS [ActivityCodeName], [f].[Id] AS [FlightId], [f].[FlightNumber], [f].[DepartureDateTimeUtc] AS [FlightDepartureDateTimeUtc], [e].[CodeName] AS [PersonExperienceCodeName], [p].[BirthDate] AS [PersonBirthDate], [f].[IsAugmentedCockpit] AS [FlightIsAugmentedCockpit], [f].[IsExtendedCockpit] AS [FlightIsExtendedCockpit], [f].[IsAugmentedCabin] AS [FlightIsAugmentedCabin], [f].[IsExtendedCabin] AS [FlightIsExtendedCabin], [f0].[Name] AS [FunctionName], CASE
    WHEN [t0].[IsHistorized] IS NULL THEN CAST(0 AS bit)
    ELSE [t0].[HasFtlErrors]
END AS [HasFtlErrors], CASE
    WHEN [t0].[IsHistorized] IS NULL THEN CAST(0 AS bit)
    ELSE [t0].[HasGavErrors]
END AS [HasGavErrors], CASE
    WHEN [t0].[IsHistorized] IS NULL THEN CAST(0 AS bit)
    ELSE [t0].[HasEasaErrors]
END AS [HasEasaErrors], CASE
    WHEN [t0].[IsHistorized] IS NULL THEN CAST(0 AS bit)
    ELSE [t0].[HasAgreementErrors]
END AS [HasAgreementErrors], CASE
    WHEN [t0].[IsHistorized] IS NULL THEN CAST(0 AS bit)
    ELSE [t0].[HasOtherErrors]
END AS [HasOtherErrors]
FROM [Rotation] AS [r]
INNER JOIN [RotationDuty] AS [r0] ON [r].[Id] = [r0].[RotationId]
INNER JOIN [Flight] AS [f] ON [r0].[FlightId] = [f].[Id]
INNER JOIN (
    SELECT [d].[Id], [d].[ActivityId], [d].[BlockTimeSec], [d].[Created], [d].[CreatedByPrincipalId], [d].[Date], [d].[DateTimeFromDiffToLt], [d].[DateTimeFromUtc], [d].[DateTimeToDiffToLt], [d].[DateTimeToUtc], [d].[DutyTimeSec], [d].[FlightId], [d].[IsHistorized], [d].[IsPendingUpdate], [d].[Modified], [d].[ModifiedByPrincipalId], [d].[PersonId], [d].[PositioningId], [d].[RequestId], [d].[RotationKey], [d].[SimulationId], [d].[Title], [d].[Type], [d].[VacationType]
    FROM [Duty] AS [d]
    WHERE [d].[IsHistorized] = @__IsHistorized_0
) AS [t] ON [f].[Id] = [t].[FlightId]
INNER JOIN [Person] AS [p] ON [t].[PersonId] = [p].[Id]
INNER JOIN [Activity] AS [a] ON [t].[ActivityId] = [a].[Id]
LEFT JOIN (
    SELECT [p0].[IsHistorized], [p0].[Date], [p0].[PersonId], [p0].[CheckinDateTimeUtc], [p0].[CheckoutDateTimeUtc], [p0].[CustomTitle], [p0].[DooType], [p0].[FdpExtensionType], [p0].[FdpTimeSecs], [p0].[HasAgreementErrors], [p0].[HasCustomCheckIn], [p0].[HasCustomCheckOut], [p0].[HasDuties], [p0].[HasEasaErrors], [p0].[HasFtlErrors], [p0].[HasGavErrors], [p0].[HasOtherErrors], [p0].[HasUrgentErrors], [p0].[HasValidationErrors], [p0].[IsAfterNightDuty], [p0].[IsBeforeNightDuty], [p0].[IsFlex], [p0].[IsFtl], [p0].[IsGav], [p0].[IsImportant], [p0].[IsNotCountableOff], [p0].[IsParty], [p0].[IsPriority], [p0].[IsValid], [p0].[IsWish], [p0].[Landing320Count], [p0].[Landing330Count], [p0].[Landing340Count], [p0].[LandingFNCCount], [p0].[Modified], [p0].[ModifiedByPrincipalId], [p0].[StaDateTimeUtc], [p0].[StdDateTimeUtc], [p0].[Timestamp]
    FROM [PersonDay] AS [p0]
    WHERE [p0].[IsHistorized] = @__IsHistorized_0
) AS [t0] ON ([t].[PersonId] = [t0].[PersonId]) AND ([t].[Date] = [t0].[Date])
LEFT JOIN (
    SELECT [p1].[Id], [p1].[DateFrom], [p1].[DateTo], [p1].[ExperienceId], [p1].[PersonId]
    FROM [PersonExperience] AS [p1]
    WHERE ([p1].[DateFrom] <= [r0].[Date]) AND (([r0].[Date] <= [p1].[DateTo]) OR [p1].[DateTo] IS NULL)
) AS [t1] ON [t].[PersonId] = [t1].[PersonId]
LEFT JOIN [Experience] AS [e] ON [t1].[ExperienceId] = [e].[Id]
LEFT JOIN (
    SELECT [p2].[Id], [p2].[DateFrom], [p2].[DateSince], [p2].[DateTo], [p2].[FunctionId], [p2].[IsTrainee], [p2].[Modified], [p2].[NewcomerAircraftTypeGroupId], [p2].[PersonId]
    FROM [PersonFunction] AS [p2]
    WHERE ([p2].[DateFrom] <= @__date_1) AND ([p2].[DateTo] IS NULL OR ([p2].[DateTo] > @__date_2))
) AS [t2] ON [p].[Id] = [t2].[PersonId]
LEFT JOIN [Function] AS [f0] ON [t2].[FunctionId] = [f0].[Id]
WHERE [r].[Id] = @__id_3

If I run it from Sql Server Management Studio I get the following errors:

Msg 4104, Level 16, State 1, Line 41
The multi-part identifier "r0.Date" could not be bound.
Msg 4104, Level 16, State 1, Line 41
The multi-part identifier "r0.Date" could not be bound.

Any ideas of how we could workaround that would be really appreciated!
Thanks

@yahorsi yahorsi changed the title Core 3.1, EF 3.1.1, SqlServer, Invalid SQL, "The multi-part identifier "r0.Date" could not be bound." Core 3.1, EF 3.1.1, SqlServer, Outer Apply, Invalid SQL, "The multi-part identifier "r0.Date" could not be bound." Feb 7, 2020
@yahorsi
Copy link
Author

yahorsi commented Feb 7, 2020

Just a note, this seems to be really critical issue, at least for us, as appeared in many places in the app, and is a show stopper to migrate to the 3.1.1. So we're rolling back.

Later I'll post few more issues (things was working on 2.2.* and stopped on 3.1.1) we have discovered while testing on 3.1.1

@ajcvickers
Copy link
Member

@smitpatel @maumar to look for workarounds.

@smitpatel
Copy link
Member

@maumar - Link me to the simpler issue you were referring.

@yahorsi
Copy link
Author

yahorsi commented Feb 7, 2020

We actually found the workaround for that concrete issue but similar popped up in other places in several microservice we migrated to the 3.1 so we had to rollback. Could you please share the results of your discussion, is it going to be fixed in 3.1?

@ajcvickers ajcvickers added this to the 5.0.0 milestone Feb 10, 2020
@ajcvickers
Copy link
Member

@maumar to find simpler issue and then assign to @smitpatel

@maumar
Copy link
Contributor

maumar commented Feb 11, 2020

@ajcvickers it's a dupe of issue I was thinking about.

@yahorsi can you provide listings for entities (especially: Rotation, RotationDuty, Flight, Duty, Experience, PersonExperience, but all entities used in the query would be ideal) and contents of OnModelCreating?

@yahorsi
Copy link
Author

yahorsi commented Feb 11, 2020

Sure, here are the models:

namespace EDW.CrewPage.Model.Database
{
    [Table("Rotation")]
    public partial class Rotation
    {
        public Rotation()
        {
            RotationCrewComplements = new HashSet<RotationCrewComplements>();
            RotationDuties = new HashSet<RotationDuty>();
        }

        public Guid Id { get; set; }

        [Required]
        [StringLength(20)]
        public string Name { get; set; }

        [Required]
        public string Routing { get; set; }

        [Column(TypeName = "date")]
        public DateTime PeriodFrom { get; set; }

        [Column(TypeName = "date")]
        public DateTime PeriodTo { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime Created { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime Modified { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime Timestamp { get; set; }

        public bool IsDeleted { get; set; }

        public bool IsForCockpit { get; set; }

        public bool IsForCabin { get; set; }

        public int Type { get; set; }

        [Required]
        [StringLength(3)]
        public string Direction { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? RotationStartDutyUtc { get; set; }

        [StringLength(5)]
        public string RotationStartDutyDiffToLt { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? RotationEndDutyUtc { get; set; }

        [StringLength(5)]
        public string RotationEndDutyDiffToLt { get; set; }

        public int DurationInDays { get; set; }

        [InverseProperty("Rotation")]
        public ICollection<RotationCrewComplements> RotationCrewComplements { get; set; }
        [InverseProperty("Rotation")]
        public ICollection<RotationDuty> RotationDuties { get; set; }
    }


    [Table("RotationDuty")]
    public partial class RotationDuty
    {

        public Guid Id { get; set; }

        public Guid RotationId { get; set; }

        [Column(TypeName = "date")]
        public DateTime Date { get; set; }

        [Required]
        [StringLength(4)]
        public string ActivityRcd { get; set; }

        [StringLength(2)]
        public string AirlineRcd { get; set; }

        public int? FlightNumber { get; set; }

        [StringLength(3)]
        public string DepartureRcd { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? DepartureUtc { get; set; }

        [StringLength(5)]
        public string DepartureDiffToLt { get; set; }

        [Required]
        [StringLength(3)]
        public string ArrivalRcd { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? ArrivalUtc { get; set; }

        [StringLength(5)]
        public string ArrivalDiffToLt { get; set; }

        public Guid? FlightId { get; set; }

        public bool IsAugmentedFlight { get; set; }

        public bool IsExtendedFlight { get; set; }

        public bool IsGav { get; set; }

        public bool IsFtl { get; set; }

        public bool IsAfterNightDuty { get; set; }

        [StringLength(50)]
        public string PositioningBy { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? StartUtc { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? EndUtc { get; set; }

        public int? PositioningType { get; set; }

        [StringLength(5)]
        public string InFlightRestTime { get; set; }

        public bool IsBeforeNightDuty { get; set; }

        [ForeignKey("FlightId")]
        [InverseProperty("RotationDuties")]
        public Flight Flight { get; set; }
        [ForeignKey("RotationId")]
        [InverseProperty("RotationDuties")]
        public Rotation Rotation { get; set; }
    }


    [Table("Flight")]
    public partial class Flight
    {
        public Flight()
        {
            AirportExperienceValidationResults = new HashSet<AirportExperienceValidationResult>();
            Comments = new HashSet<Comment>();
            Duties = new HashSet<Duty>();
            DutyLogs = new HashSet<DutyLog>();
            FlightCheckerTrainees = new HashSet<FlightCheckerTrainee>();
            FlightCheckerTraineeLogs = new HashSet<FlightCheckerTraineeLog>();
            FlightLogs = new HashSet<FlightLog>();
            RotationFirstPersonDayAggregatedDuties = new HashSet<PersonDayAggregatedDuty>();
            PersonRequestFlights = new HashSet<PersonRequestFlight>();
            Positionings = new HashSet<Positioning>();
            RotationDuties = new HashSet<RotationDuty>();
        }

        public Guid Id { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime Timestamp { get; set; }

        [Required]
        [StringLength(2)]
        public string AirlineRcd { get; set; }

        public int FlightNumber { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime ArrivalDateTimeUtc { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime DepartureDateTimeUtc { get; set; }

        [Required]
        [StringLength(3)]
        public string DestinationRcd { get; set; }

        [Required]
        [StringLength(3)]
        public string OriginRcd { get; set; }

        public bool IsDeleted { get; set; }

        [StringLength(5)]
        public string DepartureTimeDiffToLt { get; set; }

        [StringLength(5)]
        public string ArrivalTimeDiffToLt { get; set; }

        public bool? IsExtendedCockpit { get; set; }

        public bool? IsAugmentedCockpit { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? OutOfTheGateUtc { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? OffTheGroundUtc { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? OnTheGroundUtc { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? IntoTheGateUtc { get; set; }

        public int MedicalRestrictionPersonsCountCalc { get; set; }

        public int PilotsCountCalc { get; set; }

        public Guid? AircraftId { get; set; }

        public int LegSequenceNumber { get; set; }

        public Guid? OriginalId { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? EstimatedDepartureDateTimeUtc { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? EstimatedArrivalDateTimeUtc { get; set; }

        public Guid? LandingPilotFlyingId { get; set; }

        public Guid? LandingPilotMonitoringId { get; set; }

        public bool IsTypeRatingExam { get; set; }

        [Required]
        [StringLength(3)]
        public string CockpitCrewEmployer { get; set; }

        [Required]
        [StringLength(3)]
        public string CabinCrewEmployer { get; set; }

        public Guid? PlannedAircraftTypeId { get; set; }

        public bool? IsExtendedCabin { get; set; }

        public bool? IsAugmentedCabin { get; set; }

        public int PaxC { get; set; }

        public int PaxY { get; set; }

        public int AgeRulePersonsCountCalc { get; set; }

        [Column(TypeName = "date")]
        public DateTime Date { get; set; }

        public int InexperiencedPersonsCount { get; set; }

        public bool? IsLongHaulOverrider { get; set; }

        public bool IsLongHaulCalc { get; set; }

        public bool IsLongHaul { get; set; }

        [ForeignKey("AircraftId")]
        [InverseProperty("Flights")]
        public Aircraft Aircraft { get; set; }
        [ForeignKey("LandingPilotFlyingId")]
        [InverseProperty("LandingPilotFlyings")]
        public Person LandingPilotFlying { get; set; }
        [ForeignKey("LandingPilotMonitoringId")]
        [InverseProperty("LandingPilotMonitorings")]
        public Person LandingPilotMonitoring { get; set; }
        [ForeignKey("PlannedAircraftTypeId")]
        [InverseProperty("PlannedFlights")]
        public AircraftType PlannedAircraftType { get; set; }
        [InverseProperty("Flight")]
        public ICollection<AirportExperienceValidationResult> AirportExperienceValidationResults { get; set; }
        [InverseProperty("Flight")]
        public BlockedFlight BlockedFlight { get; set; }
        [InverseProperty("Flight")]
        public ICollection<Comment> Comments { get; set; }
        [InverseProperty("Flight")]
        public ICollection<Duty> Duties { get; set; }
        [InverseProperty("Flight")]
        public ICollection<DutyLog> DutyLogs { get; set; }
        [InverseProperty("Flight")]
        public ICollection<FlightCheckerTrainee> FlightCheckerTrainees { get; set; }
        [InverseProperty("Flight")]
        public ICollection<FlightCheckerTraineeLog> FlightCheckerTraineeLogs { get; set; }
        [InverseProperty("Flight")]
        public ICollection<FlightLog> FlightLogs { get; set; }
        [InverseProperty("Flight")]
        public FlightRotationExtensionCache FlightRotationExtensionCache { get; set; }
        [InverseProperty("RotationFirstFlight")]
        public ICollection<PersonDayAggregatedDuty> RotationFirstPersonDayAggregatedDuties { get; set; }
        [InverseProperty("Flight")]
        public ICollection<PersonRequestFlight> PersonRequestFlights { get; set; }
        [InverseProperty("Flight")]
        public ICollection<Positioning> Positionings { get; set; }
        [InverseProperty("Flight")]
        public ICollection<RotationDuty> RotationDuties { get; set; }
    }


    [Table("Duty")]
    public partial class Duty
    {

        public Guid PersonId { get; set; }

        public Guid? FlightId { get; set; }

        public Guid ActivityId { get; set; }

        [Column(TypeName = "date")]
        public DateTime Date { get; set; }

        public Guid Id { get; set; }

        public byte Type { get; set; }

        [Column(TypeName = "smalldatetime")]
        public DateTime? DateTimeFromUtc { get; set; }

        [Column(TypeName = "smalldatetime")]
        public DateTime? DateTimeToUtc { get; set; }

        [Required]
        [StringLength(255)]
        public string Title { get; set; }

        public int DutyTimeSec { get; set; }

        public int BlockTimeSec { get; set; }

        [StringLength(5)]
        public string DateTimeFromDiffToLt { get; set; }

        [StringLength(5)]
        public string DateTimeToDiffToLt { get; set; }

        public Guid? SimulationId { get; set; }

        public Guid? PositioningId { get; set; }

        public bool IsHistorized { get; set; }

        public Guid? RotationKey { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime Created { get; set; }

        public Guid CreatedByPrincipalId { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime Modified { get; set; }

        public Guid ModifiedByPrincipalId { get; set; }

        public byte? VacationType { get; set; }

        public bool IsPendingUpdate { get; set; }

        public Guid? RequestId { get; set; }

        [ForeignKey("ActivityId")]
        [InverseProperty("Duties")]
        public Activity Activity { get; set; }
        [ForeignKey("FlightId")]
        [InverseProperty("Duties")]
        public Flight Flight { get; set; }
        [ForeignKey("PersonId")]
        [InverseProperty("Duties")]
        public Person Person { get; set; }
        [ForeignKey("PositioningId")]
        [InverseProperty("Duties")]
        public Positioning Positioning { get; set; }
        [ForeignKey("CreatedByPrincipalId")]
        [InverseProperty("DutyCreatedBys")]
        public Principal DutyCreatedBy { get; set; }
        [ForeignKey("ModifiedByPrincipalId")]
        [InverseProperty("ModifiedBys")]
        public Principal ModifiedBy { get; set; }
        [ForeignKey("SimulationId")]
        [InverseProperty("Duties")]
        public Simulation Simulation { get; set; }
    }


    [Table("Person")]
    public partial class Person
    {
        public Person()
        {
            AirportExperienceValidationResults = new HashSet<AirportExperienceValidationResult>();
            Alerts = new HashSet<Alert>();
            AlertLogs = new HashSet<AlertLog>();
            BlockCalculationQueues = new HashSet<BlockCalculationQueue>();
            Comments = new HashSet<Comment>();
            Duties = new HashSet<Duty>();
            DutyBlocks = new HashSet<DutyBlock>();
            DutyLogs = new HashSet<DutyLog>();
            DutyValidationErrors = new HashSet<DutyValidationError>();
            LandingPilotFlyings = new HashSet<Flight>();
            LandingPilotMonitorings = new HashSet<Flight>();
            CheckerFlightCheckerTrainees = new HashSet<FlightCheckerTrainee>();
            TraineeFlightCheckerTrainees = new HashSet<FlightCheckerTrainee>();
            NewCheckerFlightCheckerTraineeLogs = new HashSet<FlightCheckerTraineeLog>();
            NewTraineeFlightCheckerTraineeLogs = new HashSet<FlightCheckerTraineeLog>();
            OldCheckerFlightCheckerTraineeLogs = new HashSet<FlightCheckerTraineeLog>();
            OldTraineeFlightCheckerTraineeLogs = new HashSet<FlightCheckerTraineeLog>();
            SelectedOnlinePrincipals = new HashSet<OnlinePrincipal>();
            PersonAircraftTypeGroupRecencies = new HashSet<PersonAircraftTypeGroupRecency>();
            PersonAircraftTypeMonthExperiences = new HashSet<PersonAircraftTypeMonthExperience>();
            PersonAirportAfterLifusMonthExperiences = new HashSet<PersonAirportAfterLifusMonthExperience>();
            PersonCheckerTrainees = new HashSet<PersonCheckerTrainee>();
            PersonContracts = new HashSet<PersonContract>();
            PersonDays = new HashSet<PersonDay>();
            PersonDayChanges = new HashSet<PersonDayChange>();
            PersonDayLogs = new HashSet<PersonDayLog>();
            PersonDayQueues = new HashSet<PersonDayQueue>();
            PersonDayShadowDuties = new HashSet<PersonDayShadowDuty>();
            PersonDestinationRestrictions = new HashSet<PersonDestinationRestriction>();
            PersonEntries = new HashSet<PersonEntry>();
            PersonExperiences = new HashSet<PersonExperience>();
            PersonFigureCacheDays = new HashSet<PersonFigureCacheDay>();
            PersonFigureCacheMonths = new HashSet<PersonFigureCacheMonth>();
            PersonFigureCacheQuarters = new HashSet<PersonFigureCacheQuarter>();
            PersonFigureCacheYears = new HashSet<PersonFigureCacheYear>();
            PersonFleets = new HashSet<PersonFleet>();
            PersonFunctions = new HashSet<PersonFunction>();
            PersonLicenses = new HashSet<PersonLicense>();
            PersonPlaningAutonomies = new HashSet<PersonPlaningAutonomy>();
            PersonPointLogs = new HashSet<PersonPointLog>();
            PersonRelatives = new HashSet<PersonRelative>();
            PersonRequestFlights = new HashSet<PersonRequestFlight>();
            PersonRequestFlightLogs = new HashSet<PersonRequestFlightLog>();
            PersonRequestOffs = new HashSet<PersonRequestOff>();
            PersonRequestOffLogs = new HashSet<PersonRequestOffLog>();
            PersonRequestVacBlocks = new HashSet<PersonRequestVacBlock>();
            PersonRequestVacBlockLogs = new HashSet<PersonRequestVacBlockLog>();
            PersonRequestVacPriorityPointsAggregateCaches = new HashSet<PersonRequestVacPriorityPointsAggregateCache>();
            PersonRevalidateDutyChanges = new HashSet<PersonRevalidateDutyChange>();
            PersonTzvLogs = new HashSet<PersonTzvLog>();
            PersonVacationLogs = new HashSet<PersonVacationLog>();
        }

        public Guid Id { get; set; }

        [Required]
        [StringLength(3)]
        public string Code { get; set; }

        [StringLength(50)]
        public string UserName { get; set; }

        [StringLength(50)]
        public string KuoniPersonalNumber { get; set; }

        [StringLength(50)]
        public string LastName { get; set; }

        [StringLength(50)]
        public string FirstName { get; set; }

        [StringLength(50)]
        public string SecondName { get; set; }

        [StringLength(50)]
        public string Department { get; set; }

        [StringLength(50)]
        public string Profession { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime Timestamp { get; set; }

        public bool IsDeleted { get; set; }

        [Column(TypeName = "date")]
        public DateTime? MedicalCheckValidTill { get; set; }

        [StringLength(3)]
        public string Nationality { get; set; }

        [StringLength(50)]
        public string PassportNumber { get; set; }

        [Column(TypeName = "date")]
        public DateTime? PassportExpiration { get; set; }

        [StringLength(3)]
        public string SecondNationality { get; set; }

        [StringLength(50)]
        public string SecondPassportNumber { get; set; }

        [Column(TypeName = "date")]
        public DateTime? SecondPassportExpiration { get; set; }

        [Column(TypeName = "date")]
        public DateTime? VisaUsaBExpiration { get; set; }

        [Column(TypeName = "date")]
        public DateTime? VisaUsaCExpiration { get; set; }

        [Column(TypeName = "date")]
        public DateTime? VisaChinaExpiration { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? BirthDate { get; set; }

        [StringLength(50)]
        public string Email { get; set; }

        [StringLength(30)]
        public string PhoneNumber { get; set; }

        public int? Gender { get; set; }

        [StringLength(10)]
        public string StaffTravelCode { get; set; }

        public Int64 SenioritySortKey { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? SeniorityOverrideDate { get; set; }

        [StringLength(30)]
        public string PhoneMobile { get; set; }

        [StringLength(30)]
        public string PhonePrivate { get; set; }

        [StringLength(30)]
        public string PhoneMobilePrivate { get; set; }

        [StringLength(30)]
        public string Phone { get; set; }

        [InverseProperty("Person")]
        public ICollection<AirportExperienceValidationResult> AirportExperienceValidationResults { get; set; }
        [InverseProperty("Person")]
        public ICollection<Alert> Alerts { get; set; }
        [InverseProperty("Person")]
        public ICollection<AlertLog> AlertLogs { get; set; }
        [InverseProperty("Person")]
        public ICollection<BlockCalculationQueue> BlockCalculationQueues { get; set; }
        [InverseProperty("Person")]
        public ICollection<Comment> Comments { get; set; }
        [InverseProperty("Person")]
        public ICollection<Duty> Duties { get; set; }
        [InverseProperty("Person")]
        public ICollection<DutyBlock> DutyBlocks { get; set; }
        [InverseProperty("Person")]
        public ICollection<DutyLog> DutyLogs { get; set; }
        [InverseProperty("Person")]
        public ICollection<DutyValidationError> DutyValidationErrors { get; set; }
        [InverseProperty("LandingPilotFlying")]
        public ICollection<Flight> LandingPilotFlyings { get; set; }
        [InverseProperty("LandingPilotMonitoring")]
        public ICollection<Flight> LandingPilotMonitorings { get; set; }
        [InverseProperty("CheckerPerson")]
        public ICollection<FlightCheckerTrainee> CheckerFlightCheckerTrainees { get; set; }
        [InverseProperty("TraineePerson")]
        public ICollection<FlightCheckerTrainee> TraineeFlightCheckerTrainees { get; set; }
        [InverseProperty("NewCheckerPerson")]
        public ICollection<FlightCheckerTraineeLog> NewCheckerFlightCheckerTraineeLogs { get; set; }
        [InverseProperty("NewTraineePerson")]
        public ICollection<FlightCheckerTraineeLog> NewTraineeFlightCheckerTraineeLogs { get; set; }
        [InverseProperty("OldCheckerPerson")]
        public ICollection<FlightCheckerTraineeLog> OldCheckerFlightCheckerTraineeLogs { get; set; }
        [InverseProperty("OldTraineePerson")]
        public ICollection<FlightCheckerTraineeLog> OldTraineeFlightCheckerTraineeLogs { get; set; }
        [InverseProperty("SelectedPerson")]
        public ICollection<OnlinePrincipal> SelectedOnlinePrincipals { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonAircraftTypeGroupRecency> PersonAircraftTypeGroupRecencies { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonAircraftTypeMonthExperience> PersonAircraftTypeMonthExperiences { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonAirportAfterLifusMonthExperience> PersonAirportAfterLifusMonthExperiences { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonCheckerTrainee> PersonCheckerTrainees { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonContract> PersonContracts { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonDay> PersonDays { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonDayChange> PersonDayChanges { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonDayLog> PersonDayLogs { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonDayQueue> PersonDayQueues { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonDayShadowDuty> PersonDayShadowDuties { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonDestinationRestriction> PersonDestinationRestrictions { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonEntry> PersonEntries { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonExperience> PersonExperiences { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonFigureCacheDay> PersonFigureCacheDays { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonFigureCacheMonth> PersonFigureCacheMonths { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonFigureCacheQuarter> PersonFigureCacheQuarters { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonFigureCacheYear> PersonFigureCacheYears { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonFleet> PersonFleets { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonFunction> PersonFunctions { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonLicense> PersonLicenses { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonPlaningAutonomy> PersonPlaningAutonomies { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonPointLog> PersonPointLogs { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonRelative> PersonRelatives { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonRequestFlight> PersonRequestFlights { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonRequestFlightLog> PersonRequestFlightLogs { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonRequestOff> PersonRequestOffs { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonRequestOffLog> PersonRequestOffLogs { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonRequestVacBlock> PersonRequestVacBlocks { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonRequestVacBlockLog> PersonRequestVacBlockLogs { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonRequestVacPriorityPointsAggregateCache> PersonRequestVacPriorityPointsAggregateCaches { get; set; }
        [InverseProperty("Person")]
        public PersonRevalidate PersonRevalidate { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonRevalidateDutyChange> PersonRevalidateDutyChanges { get; set; }
        [InverseProperty("Person")]
        public PersonSetting PersonSetting { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonTzvLog> PersonTzvLogs { get; set; }
        [InverseProperty("Person")]
        public ICollection<PersonVacationLog> PersonVacationLogs { get; set; }
    }


    [Table("Activity")]
    public partial class Activity
    {
        public Activity()
        {
            AircraftTypeLicenseActivities = new HashSet<AircraftTypeLicenseActivity>();
            AirportExperienceConditionGroups = new HashSet<AirportExperienceConditionGroup>();
            AirportExperienceRules = new HashSet<AirportExperienceRule>();
            AirportLicenseActivities = new HashSet<AirportLicenseActivity>();
            Duties = new HashSet<Duty>();
            DutyBlocks = new HashSet<DutyBlock>();
            NewDutyLogs = new HashSet<DutyLog>();
            OldDutyLogs = new HashSet<DutyLog>();
            PersonAircraftTypeMonthExperiences = new HashSet<PersonAircraftTypeMonthExperience>();
            PersonCheckerTrainees = new HashSet<PersonCheckerTrainee>();
            PersonRevalidateDutyChanges = new HashSet<PersonRevalidateDutyChange>();
        }

        public Guid Id { get; set; }

        [Required]
        [StringLength(10)]
        public string CodeName { get; set; }

        public int Type { get; set; }

        public bool IsCabin { get; set; }

        public bool IsCockpit { get; set; }

        [InverseProperty("Activity")]
        public ICollection<AircraftTypeLicenseActivity> AircraftTypeLicenseActivities { get; set; }
        [InverseProperty("Activity")]
        public ICollection<AirportExperienceConditionGroup> AirportExperienceConditionGroups { get; set; }
        [InverseProperty("Activity")]
        public ICollection<AirportExperienceRule> AirportExperienceRules { get; set; }
        [InverseProperty("Activity")]
        public ICollection<AirportLicenseActivity> AirportLicenseActivities { get; set; }
        [InverseProperty("Activity")]
        public ICollection<Duty> Duties { get; set; }
        [InverseProperty("Activity")]
        public ICollection<DutyBlock> DutyBlocks { get; set; }
        [InverseProperty("NewActivity")]
        public ICollection<DutyLog> NewDutyLogs { get; set; }
        [InverseProperty("OldActivity")]
        public ICollection<DutyLog> OldDutyLogs { get; set; }
        [InverseProperty("Activity")]
        public ICollection<PersonAircraftTypeMonthExperience> PersonAircraftTypeMonthExperiences { get; set; }
        [InverseProperty("Activity")]
        public ICollection<PersonCheckerTrainee> PersonCheckerTrainees { get; set; }
        [InverseProperty("Activity")]
        public ICollection<PersonRevalidateDutyChange> PersonRevalidateDutyChanges { get; set; }
    }


    [Table("PersonDay")]
    public partial class PersonDay
    {

        [Key]
        [Column(TypeName = "date")]
        public DateTime Date { get; set; }

        [Key]
        public Guid PersonId { get; set; }

        public bool IsNotCountableOff { get; set; }

        [Column(TypeName = "smalldatetime")]
        public DateTime? CheckinDateTimeUtc { get; set; }

        [Column(TypeName = "smalldatetime")]
        public DateTime? CheckoutDateTimeUtc { get; set; }

        public bool IsWish { get; set; }

        public bool IsPriority { get; set; }

        public bool IsImportant { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime Modified { get; set; }

        public Guid ModifiedByPrincipalId { get; set; }

        public bool IsGav { get; set; }

        public bool IsFtl { get; set; }

        public bool IsFlex { get; set; }

        [Key]
        public bool IsHistorized { get; set; }

        public bool IsAfterNightDuty { get; set; }

        public bool IsBeforeNightDuty { get; set; }

        public bool HasCustomCheckIn { get; set; }

        public bool HasCustomCheckOut { get; set; }

        public bool HasDuties { get; set; }

        [StringLength(10)]
        public string CustomTitle { get; set; }

        public bool HasValidationErrors { get; set; }

        public bool HasFtlErrors { get; set; }

        public bool HasGavErrors { get; set; }

        public bool HasAgreementErrors { get; set; }

        public bool HasOtherErrors { get; set; }

        public bool IsParty { get; set; }

        public byte FdpExtensionType { get; set; }

        public bool HasUrgentErrors { get; set; }

        public int FdpTimeSecs { get; set; }

        [Column(TypeName = "smalldatetime")]
        public DateTime? StdDateTimeUtc { get; set; }

        [Column(TypeName = "smalldatetime")]
        public DateTime? StaDateTimeUtc { get; set; }

        public byte Landing320Count { get; set; }

        public byte Landing330Count { get; set; }

        public byte Landing340Count { get; set; }

        public byte DooType { get; set; }

        public byte LandingFNCCount { get; set; }

        public bool HasEasaErrors { get; set; }

        public bool IsValid { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime Timestamp { get; set; }

        [ForeignKey("PersonId")]
        [InverseProperty("PersonDays")]
        public Person Person { get; set; }
        [ForeignKey("ModifiedByPrincipalId")]
        [InverseProperty("PersonDateModifiedBys")]
        public Principal PersonDateModifiedBy { get; set; }
    }


    [Table("PersonExperience")]
    public partial class PersonExperience
    {

        public Guid Id { get; set; }

        public Guid PersonId { get; set; }

        public Guid ExperienceId { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime DateFrom { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime? DateTo { get; set; }

        [ForeignKey("ExperienceId")]
        [InverseProperty("PersonExperiences")]
        public Experience Experience { get; set; }
        [ForeignKey("PersonId")]
        [InverseProperty("PersonExperiences")]
        public Person Person { get; set; }
    }


    [Table("Experience")]
    public partial class Experience
    {
        public Experience()
        {
            PersonExperiences = new HashSet<PersonExperience>();
        }

        public Guid Id { get; set; }

        [Required]
        [StringLength(10)]
        public string CodeName { get; set; }

        [Required]
        [StringLength(20)]
        public string DisplayName { get; set; }

        [StringLength(50)]
        public string Description { get; set; }

        [InverseProperty("Experience")]
        public ICollection<PersonExperience> PersonExperiences { get; set; }
    }


    [Table("PersonFunction")]
    public partial class PersonFunction
    {

        public Guid Id { get; set; }

        public Guid PersonId { get; set; }

        public Guid FunctionId { get; set; }

        [Column(TypeName = "date")]
        public DateTime DateFrom { get; set; }

        [Column(TypeName = "date")]
        public DateTime? DateTo { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime Modified { get; set; }

        [Column(TypeName = "date")]
        public DateTime DateSince { get; set; }

        public bool IsTrainee { get; set; }

        public Guid? NewcomerAircraftTypeGroupId { get; set; }

        [ForeignKey("NewcomerAircraftTypeGroupId")]
        [InverseProperty("PersonFunctions")]
        public AircraftTypeGroup AircraftTypeGroup { get; set; }
        [ForeignKey("FunctionId")]
        [InverseProperty("PersonFunctions")]
        public Function Function { get; set; }
        [ForeignKey("PersonId")]
        [InverseProperty("PersonFunctions")]
        public Person Person { get; set; }
    }


    [Table("Function")]
    public partial class Function
    {
        public Function()
        {
            AvailableVacationsCounts = new HashSet<AvailableVacationsCount>();
            FunctionLicenses = new HashSet<FunctionLicense>();
            PersonFunctions = new HashSet<PersonFunction>();
            PersonRequestFlights = new HashSet<PersonRequestFlight>();
            RequestCapacities = new HashSet<RequestCapacity>();
            RequestCapacityLicenseDistributions = new HashSet<RequestCapacityLicenseDistribution>();
        }

        public Guid Id { get; set; }

        [Required]
        [StringLength(3)]
        public string Name { get; set; }

        public Guid? FunctionGroupId { get; set; }

        [ForeignKey("FunctionGroupId")]
        [InverseProperty("Functions")]
        public FunctionGroup FunctionGroup { get; set; }
        [InverseProperty("Function")]
        public ICollection<AvailableVacationsCount> AvailableVacationsCounts { get; set; }
        [InverseProperty("Function")]
        public ICollection<FunctionLicense> FunctionLicenses { get; set; }
        [InverseProperty("Function")]
        public ICollection<PersonFunction> PersonFunctions { get; set; }
        [InverseProperty("Function")]
        public ICollection<PersonRequestFlight> PersonRequestFlights { get; set; }
        [InverseProperty("Function")]
        public ICollection<RequestCapacity> RequestCapacities { get; set; }
        [InverseProperty("Function")]
        public ICollection<RequestCapacityLicenseDistribution> RequestCapacityLicenseDistributions { get; set; }
    }
}

And OnModelCreating (a bit big but better to have all info than some missing ) )

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Activity>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.CodeName).IsUnicode(false);
            });
            modelBuilder.Entity<Aircraft>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.RegistrationNumber).IsUnicode(false);
                entity.HasOne(d => d.AircraftType)
                    .WithMany(p => p.Aircrafts)
                    .HasForeignKey(d => d.AircraftTypeId)
                    .HasConstraintName("FK_Aircraft_AircraftType");
            });
            modelBuilder.Entity<AircraftMaintenance>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Aircraft)
                    .WithMany(p => p.AircraftMaintenances)
                    .HasForeignKey(d => d.AircraftId)
                    .HasConstraintName("FK_AircraftMaintenance_Aircraft");
            });
            modelBuilder.Entity<AircraftType>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.CodeName).IsUnicode(false);
                entity.HasOne(d => d.AircraftTypeGroup)
                    .WithMany(p => p.AircraftTypes)
                    .HasForeignKey(d => d.AircraftTypeGroupId)
                    .HasConstraintName("FK_AircraftType_AircraftTypeGroup");
                entity.HasOne(d => d.RestFacility)
                    .WithMany(p => p.AircraftTypes)
                    .HasForeignKey(d => d.RestFacilityId)
                    .HasConstraintName("FK_AircraftType_RestFacility");
            });
            modelBuilder.Entity<AircraftTypeGroup>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.Name).IsUnicode(false);
            });
            modelBuilder.Entity<AircraftTypeLicenseActivity>(entity =>
            {
                entity.HasKey(e => new { e.AircraftTypeId, e.LicenseId, e.ActivityId });
                entity.HasOne(d => d.Activity)
                    .WithMany(p => p.AircraftTypeLicenseActivities)
                    .HasForeignKey(d => d.ActivityId)
                    .HasConstraintName("FK_AircraftTypeLicenseActivity_Activity");
                entity.HasOne(d => d.AircraftType)
                    .WithMany(p => p.AircraftTypeLicenseActivities)
                    .HasForeignKey(d => d.AircraftTypeId)
                    .HasConstraintName("FK_AircraftTypeLicenseActivity_AircraftType");
                entity.HasOne(d => d.License)
                    .WithMany(p => p.AircraftTypeLicenseActivities)
                    .HasForeignKey(d => d.LicenseId)
                    .HasConstraintName("FK_AircraftTypeLicenseActivity_License");
            });
            modelBuilder.Entity<Airport>(entity =>
            {
                entity.Property(e => e.FourLetterCode).IsUnicode(false);
                entity.Property(e => e.CountryCode).IsUnicode(false);
                entity.Property(e => e.ThreeLetterCode).IsUnicode(false);
            });
            modelBuilder.Entity<AirportCrewHotel>(entity =>
            {
                entity.HasKey(e => new { e.FourLetterCode, e.DetailType });
                entity.Property(e => e.FourLetterCode).IsUnicode(false);
                entity.Property(e => e.DetailType).ValueGeneratedNever();
                entity.HasOne(d => d.Airport)
                    .WithMany(p => p.AirportCrewHotels)
                    .HasForeignKey(d => d.FourLetterCode)
                    .HasConstraintName("FK_AirportCrewHotel_Airport");
            });
            modelBuilder.Entity<AirportExperienceCondition>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.AirportExperienceConditionGroup)
                    .WithMany(p => p.AirportExperienceConditions)
                    .HasForeignKey(d => d.ConditionGroupId)
                    .HasConstraintName("FK_AirportExperienceCondition_AirportExperienceConditionGroup");
                entity.HasOne(d => d.AirportExperienceConditionType)
                    .WithMany(p => p.AirportExperienceConditions)
                    .HasForeignKey(d => d.TypeId)
                    .HasConstraintName("FK_AirportExperienceCondition_AirportExperienceConditionType");
            });
            modelBuilder.Entity<AirportExperienceConditionGroup>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Activity)
                    .WithMany(p => p.AirportExperienceConditionGroups)
                    .HasForeignKey(d => d.ActivityId)
                    .HasConstraintName("FK_AirportExperienceConditionGroup_Activity");
                entity.HasOne(d => d.AirportExperienceRule)
                    .WithMany(p => p.AirportExperienceConditionGroups)
                    .HasForeignKey(d => d.RuleId)
                    .HasConstraintName("FK_AirportExperienceConditionGroup_AirportExperienceRule");
            });
            modelBuilder.Entity<AirportExperienceConditionType>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
            });
            modelBuilder.Entity<AirportExperienceRule>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Activity)
                    .WithMany(p => p.AirportExperienceRules)
                    .HasForeignKey(d => d.ApplicableActivityId)
                    .HasConstraintName("FK_AirportExperienceRule_Activity");
            });
            modelBuilder.Entity<AirportExperienceRuleAirport>(entity =>
            {
                entity.HasKey(e => new { e.RuleId, e.AirportFourLetterCode });
                entity.Property(e => e.AirportFourLetterCode).IsUnicode(false);
                entity.HasOne(d => d.Airport)
                    .WithMany(p => p.AirportExperienceRuleAirports)
                    .HasForeignKey(d => d.AirportFourLetterCode)
                    .HasConstraintName("FK_AirportExperienceRule_Airport");
                entity.HasOne(d => d.AirportExperienceRule)
                    .WithMany(p => p.AirportExperienceRuleAirports)
                    .HasForeignKey(d => d.RuleId)
                    .HasConstraintName("FK_AirportExperienceRuleAirport_AirportExperienceRule");
            });
            modelBuilder.Entity<AirportExperienceValidationResult>(entity =>
            {
                entity.HasKey(e => new { e.RuleId, e.FlightId, e.PersonId });
                entity.HasOne(d => d.AirportExperienceRule)
                    .WithMany(p => p.AirportExperienceValidationResults)
                    .HasForeignKey(d => d.RuleId)
                    .HasConstraintName("FK_AirportExperienceValidationResult_AirportExperienceRule");
                entity.HasOne(d => d.Flight)
                    .WithMany(p => p.AirportExperienceValidationResults)
                    .HasForeignKey(d => d.FlightId)
                    .HasConstraintName("FK_AirportExperienceValidationResult_Flight");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.AirportExperienceValidationResults)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_AirportExperienceValidationResult_Person");
            });
            modelBuilder.Entity<AirportLicenseActivity>(entity =>
            {
                entity.HasKey(e => new { e.AirportFourLetterCodeAirport, e.LicenseId, e.ActivityId });
                entity.Property(e => e.AirportFourLetterCodeAirport).IsUnicode(false);
                entity.HasOne(d => d.Activity)
                    .WithMany(p => p.AirportLicenseActivities)
                    .HasForeignKey(d => d.ActivityId)
                    .HasConstraintName("FK_AirportLicenseActivity_Activity");
                entity.HasOne(d => d.Airport)
                    .WithMany(p => p.AirportLicenseActivities)
                    .HasForeignKey(d => d.AirportFourLetterCodeAirport)
                    .HasConstraintName("FK_AirportLicenseActivity_Airport");
                entity.HasOne(d => d.License)
                    .WithMany(p => p.AirportLicenseActivities)
                    .HasForeignKey(d => d.LicenseId)
                    .HasConstraintName("FK_AirportLicenseActivity_License");
            });
            modelBuilder.Entity<Alert>(entity =>
            {
                entity.HasKey(e => new { e.PersonId, e.AlertTypeId });
                entity.HasOne(d => d.AlertType)
                    .WithMany(p => p.Alerts)
                    .HasForeignKey(d => d.AlertTypeId)
                    .HasConstraintName("FK_Alert_AlertType");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.Alerts)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_Alert_Person");
            });
            modelBuilder.Entity<AlertLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.AlertType)
                    .WithMany(p => p.AlertLogs)
                    .HasForeignKey(d => d.AlertTypeId)
                    .HasConstraintName("FK_AlertLog_AlertType");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.AlertLogs)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_AlertLog_Person");
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.AlertLogs)
                    .HasForeignKey(d => d.ModifiedByPrincipalId)
                    .HasConstraintName("FK_AlertLog_Principal");
            });
            modelBuilder.Entity<AlertType>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
            });
            modelBuilder.Entity<AvailableVacationsCount>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Function)
                    .WithMany(p => p.AvailableVacationsCounts)
                    .HasForeignKey(d => d.FunctionId)
                    .HasConstraintName("FK_AvailableVacationsCount_Function");
                entity.HasOne(d => d.LicenseGroup)
                    .WithMany(p => p.AvailableVacationsCounts)
                    .HasForeignKey(d => d.LicenseGroupId)
                    .HasConstraintName("FK_AvailableVacationsCount_LicenseGroup");
            });
            modelBuilder.Entity<BlockCalculationQueue>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.BlockCalculationQueues)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_BlockCalculationQueue_Person");
            });
            modelBuilder.Entity<BlockedDay>(entity =>
            {
                entity.Property(e => e.Date).ValueGeneratedNever();
            });
            modelBuilder.Entity<BlockedFlight>(entity =>
            {
                entity.Property(e => e.Date).HasComputedColumnSql("(isnull(datefromparts((2000)+CONVERT([smallint],CONVERT([varbinary](1),[FlightId])),CONVERT([int],substring(CONVERT([varbinary](3),[FlightId]),(2),(1))),CONVERT([int],substring(CONVERT([varbinary](3),[FlightId]),(3),(1)))),datefromparts((2000),(1),(1))))");
                entity.HasOne(d => d.Flight)
                    .WithOne(p => p.BlockedFlight)
                    .HasForeignKey<BlockedFlight>(d => d.FlightId)
                    .HasConstraintName("FK_BlockedFlight_Flight");
            });
            modelBuilder.Entity<CalendarDate>(entity =>
            {
                entity.Property(e => e.Date).ValueGeneratedNever();
            });
            modelBuilder.Entity<Comment>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Flight)
                    .WithMany(p => p.Comments)
                    .HasForeignKey(d => d.FlightId)
                    .HasConstraintName("FK_Comment_Flight");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.Comments)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_Comment_Person");
                entity.HasOne(d => d.CommentCreatedBy)
                    .WithMany(p => p.CommentCreatedBys)
                    .HasForeignKey(d => d.CreatedByPrincipalId)
                    .HasConstraintName("FK_Comment_Principal_CommentCreatedBy");
                entity.HasOne(d => d.CommentModifiedBy)
                    .WithMany(p => p.CommentModifiedBys)
                    .HasForeignKey(d => d.ModifiedByPrincipalId)
                    .HasConstraintName("FK_Comment_Principal_CommentModifiedBy");
            });
            modelBuilder.Entity<Configuration>(entity =>
            {
                entity.HasKey(e => new { e.Key, e.Group });
                entity.Property(e => e.Key).IsUnicode(false);
                entity.Property(e => e.Group).IsUnicode(false);
            });
            modelBuilder.Entity<DatabaseVersion>(entity =>
            {
                entity.Property(e => e.TimeStamp).ValueGeneratedNever();
            });
            modelBuilder.Entity<Duty>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.DateTimeFromDiffToLt).IsUnicode(false);
                entity.Property(e => e.DateTimeToDiffToLt).IsUnicode(false);
                entity.HasOne(d => d.Activity)
                    .WithMany(p => p.Duties)
                    .HasForeignKey(d => d.ActivityId)
                    .HasConstraintName("FK_Duty_Activity");
                entity.HasOne(d => d.Flight)
                    .WithMany(p => p.Duties)
                    .HasForeignKey(d => d.FlightId)
                    .HasConstraintName("FK_Duty_Flight");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.Duties)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_Duty_Person");
                entity.HasOne(d => d.Positioning)
                    .WithMany(p => p.Duties)
                    .HasForeignKey(d => d.PositioningId)
                    .HasConstraintName("FK_Duty_Positioning");
                entity.HasOne(d => d.DutyCreatedBy)
                    .WithMany(p => p.DutyCreatedBys)
                    .HasForeignKey(d => d.CreatedByPrincipalId)
                    .HasConstraintName("FK_Duty_Principal_DutyCreatedBy");
                entity.HasOne(d => d.ModifiedBy)
                    .WithMany(p => p.ModifiedBys)
                    .HasForeignKey(d => d.ModifiedByPrincipalId)
                    .HasConstraintName("FK_Duty_Principal_ModifiedBy");
                entity.HasOne(d => d.Simulation)
                    .WithMany(p => p.Duties)
                    .HasForeignKey(d => d.SimulationId)
                    .HasConstraintName("FK_Duty_Simulation");
            });
            modelBuilder.Entity<DutyBlock>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Activity)
                    .WithMany(p => p.DutyBlocks)
                    .HasForeignKey(d => d.ActivityId)
                    .HasConstraintName("FK_VacationBlock_Activity");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.DutyBlocks)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_VacationBlock_Person");
            });
            modelBuilder.Entity<DutyLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.NewDateTimeFromDiffToLt).IsUnicode(false);
                entity.Property(e => e.NewDateTimeToDiffToLt).IsUnicode(false);
                entity.Property(e => e.OldDateTimeFromDiffToLt).IsUnicode(false);
                entity.Property(e => e.OldDateTimeToDiffToLt).IsUnicode(false);
                entity.HasOne(d => d.Flight)
                    .WithMany(p => p.DutyLogs)
                    .HasForeignKey(d => d.FlightId)
                    .HasConstraintName("FK_DutyLog_Flight");
                entity.HasOne(d => d.NewActivity)
                    .WithMany(p => p.NewDutyLogs)
                    .HasForeignKey(d => d.NewActivityId)
                    .HasConstraintName("FK_DutyLog_NewActivity");
                entity.HasOne(d => d.NewPositioning)
                    .WithMany(p => p.NewDutyLogs)
                    .HasForeignKey(d => d.NewPositioningId)
                    .HasConstraintName("FK_DutyLog_NewPositioning");
                entity.HasOne(d => d.NewSimulation)
                    .WithMany(p => p.NewDutyLogs)
                    .HasForeignKey(d => d.NewSimulationId)
                    .HasConstraintName("FK_DutyLog_NewSimulation");
                entity.HasOne(d => d.OldActivity)
                    .WithMany(p => p.OldDutyLogs)
                    .HasForeignKey(d => d.OldActivityId)
                    .HasConstraintName("FK_DutyLog_OldActivity");
                entity.HasOne(d => d.OldPositioning)
                    .WithMany(p => p.OldDutyLogs)
                    .HasForeignKey(d => d.OldPositioningId)
                    .HasConstraintName("FK_DutyLog_OldPositioning");
                entity.HasOne(d => d.OldSimulation)
                    .WithMany(p => p.OldDutyLogs)
                    .HasForeignKey(d => d.OldSimulationId)
                    .HasConstraintName("FK_DutyLog_OldSimulation");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.DutyLogs)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_DutyLog_Person");
                entity.HasOne(d => d.DutyLogModifiedBy)
                    .WithMany(p => p.DutyLogModifiedBys)
                    .HasForeignKey(d => d.ModifiedByPrincipalId)
                    .HasConstraintName("FK_DutyLog_Principal_DutyLogModifiedBy");
            });
            modelBuilder.Entity<DutyRequestCache>(entity =>
            {
                entity.Property(e => e.RequestId).ValueGeneratedNever();
            });
            modelBuilder.Entity<DutyValidationError>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.SuppressReason).HasDefaultValueSql("((0))");
                entity.HasOne(d => d.Comment)
                    .WithMany(p => p.DutyValidationErrors)
                    .HasForeignKey(d => d.CommentId)
                    .HasConstraintName("FK_DutyValidationError_Comment");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.DutyValidationErrors)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_DutyValidationError_Person");
            });
            modelBuilder.Entity<DutyValidationErrorOperation>(entity =>
            {
                entity.HasKey(e => new { e.DutyValidationErrorId, e.OperationId });
                entity.HasOne(d => d.DutyValidationError)
                    .WithMany(p => p.DutyValidationErrorOperations)
                    .HasForeignKey(d => d.DutyValidationErrorId)
                    .HasConstraintName("FK_DutyValidationErrorOperation_DutyValidationError");
                entity.HasOne(d => d.Operation)
                    .WithMany(p => p.DutyValidationErrorOperations)
                    .HasForeignKey(d => d.OperationId)
                    .HasConstraintName("FK_DutyValidationErrorOperation_Operation");
            });
            modelBuilder.Entity<Experience>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.CodeName).IsUnicode(false);
            });
            modelBuilder.Entity<Flight>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.AirlineRcd).IsUnicode(false);
                entity.Property(e => e.ArrivalTimeDiffToLt).IsUnicode(false);
                entity.Property(e => e.CabinCrewEmployer).IsUnicode(false);
                entity.Property(e => e.CockpitCrewEmployer).IsUnicode(false);
                entity.Property(e => e.Date).HasComputedColumnSql("(datefromparts((2000)+CONVERT([smallint],CONVERT([varbinary](1),[Id])),CONVERT([int],substring(CONVERT([varbinary](3),[Id]),(2),(1))),CONVERT([int],substring(CONVERT([varbinary](3),[Id]),(3),(1)))))");
                entity.Property(e => e.DepartureTimeDiffToLt).IsUnicode(false);
                entity.Property(e => e.DestinationRcd).IsUnicode(false);
                entity.Property(e => e.IsLongHaul).HasComputedColumnSql("(isnull([IsLongHaulOverrider],[IsLongHaulCalc]))");
                entity.Property(e => e.OriginRcd).IsUnicode(false);
                entity.HasOne(d => d.Aircraft)
                    .WithMany(p => p.Flights)
                    .HasForeignKey(d => d.AircraftId)
                    .HasConstraintName("FK_Flight_Aircraft");
                entity.HasOne(d => d.LandingPilotFlying)
                    .WithMany(p => p.LandingPilotFlyings)
                    .HasForeignKey(d => d.LandingPilotFlyingId)
                    .HasConstraintName("FK_Flight_LandingPilotFlyingId");
                entity.HasOne(d => d.LandingPilotMonitoring)
                    .WithMany(p => p.LandingPilotMonitorings)
                    .HasForeignKey(d => d.LandingPilotMonitoringId)
                    .HasConstraintName("FK_Flight_LandingPilotMonitoringId");
                entity.HasOne(d => d.PlannedAircraftType)
                    .WithMany(p => p.PlannedFlights)
                    .HasForeignKey(d => d.PlannedAircraftTypeId)
                    .HasConstraintName("FK_Flight_PlannedAircraftType");
            });
            modelBuilder.Entity<FlightCheckerTrainee>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.CheckerPerson)
                    .WithMany(p => p.CheckerFlightCheckerTrainees)
                    .HasForeignKey(d => d.CheckerPersonId)
                    .HasConstraintName("FK_FlightCheckerTrainee_CheckerPerson");
                entity.HasOne(d => d.Flight)
                    .WithMany(p => p.FlightCheckerTrainees)
                    .HasForeignKey(d => d.FlightId)
                    .HasConstraintName("FK_FlightCheckerTrainee_Flight");
                entity.HasOne(d => d.TraineePerson)
                    .WithMany(p => p.TraineeFlightCheckerTrainees)
                    .HasForeignKey(d => d.TraineePersonId)
                    .HasConstraintName("FK_FlightCheckerTrainee_TraineePerson");
            });
            modelBuilder.Entity<FlightCheckerTraineeLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Flight)
                    .WithMany(p => p.FlightCheckerTraineeLogs)
                    .HasForeignKey(d => d.FlightId)
                    .HasConstraintName("FK_FlightCheckerTraineeLog_Flight");
                entity.HasOne(d => d.NewCheckerPerson)
                    .WithMany(p => p.NewCheckerFlightCheckerTraineeLogs)
                    .HasForeignKey(d => d.NewCheckerPersonId)
                    .HasConstraintName("FK_FlightCheckerTraineeLog_NewCheckerPerson");
                entity.HasOne(d => d.NewTraineePerson)
                    .WithMany(p => p.NewTraineeFlightCheckerTraineeLogs)
                    .HasForeignKey(d => d.NewTraineePersonId)
                    .HasConstraintName("FK_FlightCheckerTraineeLog_NewTraineePerson");
                entity.HasOne(d => d.OldCheckerPerson)
                    .WithMany(p => p.OldCheckerFlightCheckerTraineeLogs)
                    .HasForeignKey(d => d.OldCheckerPersonId)
                    .HasConstraintName("FK_FlightCheckerTraineeLog_OldCheckerPerson");
                entity.HasOne(d => d.OldTraineePerson)
                    .WithMany(p => p.OldTraineeFlightCheckerTraineeLogs)
                    .HasForeignKey(d => d.OldTraineePersonId)
                    .HasConstraintName("FK_FlightCheckerTraineeLog_OldTraineePerson");
                entity.HasOne(d => d.FlightCheckerTraineeLogModifiedBy)
                    .WithMany(p => p.FlightCheckerTraineeLogModifiedBys)
                    .HasForeignKey(d => d.ModifiedByPrincipalId)
                    .HasConstraintName("FK_FlightCheckerTraineeLog_Principal_FlightCheckerTraineeLogModifiedBy");
            });
            modelBuilder.Entity<FlightFunctionRotation>(entity =>
            {
                entity.HasKey(e => new { e.FlightId, e.FunctionId });
                entity.Property(e => e.FlightId).ValueGeneratedNever();
                entity.Property(e => e.FunctionId).ValueGeneratedNever();
            });
            modelBuilder.Entity<FlightHistorized>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.ArrivalTimeDiffToLt).IsUnicode(false);
                entity.Property(e => e.CabinCrewEmployer).IsUnicode(false);
                entity.Property(e => e.CockpitCrewEmployer).IsUnicode(false);
                entity.Property(e => e.DepartureTimeDiffToLt).IsUnicode(false);
            });
            modelBuilder.Entity<FlightLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Flight)
                    .WithMany(p => p.FlightLogs)
                    .HasForeignKey(d => d.FlightId)
                    .HasConstraintName("FK_FlightLog_Flight");
            });
            modelBuilder.Entity<FlightRotationExtensionCache>(entity =>
            {
                entity.HasOne(d => d.Flight)
                    .WithOne(p => p.FlightRotationExtensionCache)
                    .HasForeignKey<FlightRotationExtensionCache>(d => d.FlightId)
                    .HasConstraintName("FK_FlightRotationExtensionCache_Flight");
            });
            modelBuilder.Entity<Function>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.Name).IsUnicode(false);
                entity.HasOne(d => d.FunctionGroup)
                    .WithMany(p => p.Functions)
                    .HasForeignKey(d => d.FunctionGroupId)
                    .HasConstraintName("FK_Function_FunctionGroup");
            });
            modelBuilder.Entity<FunctionGroup>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.IsForCabin).HasComputedColumnSql("(case [Name] when 'Cabin' then (1) else (0) end)");
            });
            modelBuilder.Entity<FunctionLicense>(entity =>
            {
                entity.HasKey(e => new { e.FunctionId, e.LicenseId });
                entity.HasOne(d => d.Function)
                    .WithMany(p => p.FunctionLicenses)
                    .HasForeignKey(d => d.FunctionId)
                    .HasConstraintName("FK_FunctionLicense_Function");
                entity.HasOne(d => d.License)
                    .WithMany(p => p.FunctionLicenses)
                    .HasForeignKey(d => d.LicenseId)
                    .HasConstraintName("FK_FunctionLicense_License");
            });
            modelBuilder.Entity<Job>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.Type).IsUnicode(false);
            });
            modelBuilder.Entity<JobExecution>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.TriggerName).IsUnicode(false);
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.JobExecutions)
                    .HasForeignKey(d => d.PrincipalId)
                    .HasConstraintName("FK_JobExecution_Principal");
            });
            modelBuilder.Entity<JobSchedule>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Job)
                    .WithMany(p => p.JobSchedules)
                    .HasForeignKey(d => d.JobId)
                    .HasConstraintName("FK_JobSchedule_Job");
            });
            modelBuilder.Entity<License>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.ShortNameNeutral).HasDefaultValueSql("('')");
            });
            modelBuilder.Entity<LicenseGroup>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
            });
            modelBuilder.Entity<LicenseLicenseGroup>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.License)
                    .WithMany(p => p.LicenseLicenseGroups)
                    .HasForeignKey(d => d.LicenseId)
                    .HasConstraintName("FK_LicenseLicenseGroup_License");
                entity.HasOne(d => d.LicenseGroup)
                    .WithMany(p => p.LicenseLicenseGroups)
                    .HasForeignKey(d => d.LicenseGroupId)
                    .HasConstraintName("FK_LicenseLicenseGroup_LicenseGroup");
            });
            modelBuilder.Entity<MailQueue>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.PersonRequestVacBlock)
                    .WithMany(p => p.MailQueues)
                    .HasForeignKey(d => d.PersonRequestVacBlockId)
                    .HasConstraintName("FK_MailQueue_PersonRequestVacBlock");
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.MailQueues)
                    .HasForeignKey(d => d.CreatedByPrincipalId)
                    .HasConstraintName("FK_MailQueue_Principal");
            });
            modelBuilder.Entity<OnlinePrincipal>(entity =>
            {
                entity.Property(e => e.ConnectionId).IsUnicode(false);
                entity.Property(e => e.SelectedPersonCode).IsUnicode(false);
                entity.HasOne(d => d.SelectedPerson)
                    .WithMany(p => p.SelectedOnlinePrincipals)
                    .HasForeignKey(d => d.SelectedPersonId)
                    .HasConstraintName("FK_OnlinePrincipal_SelectedPersonId");
            });
            modelBuilder.Entity<Operation>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.IsSystem).HasDefaultValueSql("((0))");
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.Operations)
                    .HasForeignKey(d => d.PrincipalId)
                    .HasConstraintName("FK_Operation_Principal");
            });
            modelBuilder.Entity<Person>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.Code).IsUnicode(false);
                entity.Property(e => e.KuoniPersonalNumber).IsUnicode(false);
                entity.Property(e => e.Nationality).IsUnicode(false);
                entity.Property(e => e.PassportNumber).IsUnicode(false);
                entity.Property(e => e.Phone).IsUnicode(false);
                entity.Property(e => e.PhoneMobile).IsUnicode(false);
                entity.Property(e => e.PhoneMobilePrivate).IsUnicode(false);
                entity.Property(e => e.PhoneNumber).IsUnicode(false);
                entity.Property(e => e.PhonePrivate).IsUnicode(false);
                entity.Property(e => e.SecondNationality).IsUnicode(false);
                entity.Property(e => e.SecondPassportNumber).IsUnicode(false);
                entity.Property(e => e.UserName).IsUnicode(false);
            });
            modelBuilder.Entity<PersonAircraftTypeGroupLanding>(entity =>
            {
                entity.HasKey(e => new { e.PersonId, e.Date, e.AircraftTypeGroupId, e.Type });
                entity.Property(e => e.PersonId).ValueGeneratedNever();
                entity.Property(e => e.Date).ValueGeneratedNever();
                entity.Property(e => e.AircraftTypeGroupId).ValueGeneratedNever();
                entity.Property(e => e.Type).ValueGeneratedNever();
            });
            modelBuilder.Entity<PersonAircraftTypeGroupRecency>(entity =>
            {
                entity.HasKey(e => new { e.PersonId, e.AircraftTypeGroupId });
                entity.HasOne(d => d.AircraftTypeGroup)
                    .WithMany(p => p.PersonAircraftTypeGroupRecencies)
                    .HasForeignKey(d => d.AircraftTypeGroupId)
                    .HasConstraintName("FK_PersonAircraftTypeGroupRecency_AircraftTypeGroup");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonAircraftTypeGroupRecencies)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonAircraftTypeGroupRecency_Person");
            });
            modelBuilder.Entity<PersonAircraftTypeMonthExperience>(entity =>
            {
                entity.HasKey(e => new { e.PersonId, e.Year, e.Month, e.AircraftTypeGroupId, e.ActivityId });
                entity.Property(e => e.Year).ValueGeneratedNever();
                entity.Property(e => e.Month).ValueGeneratedNever();
                entity.HasOne(d => d.Activity)
                    .WithMany(p => p.PersonAircraftTypeMonthExperiences)
                    .HasForeignKey(d => d.ActivityId)
                    .HasConstraintName("FK_PersonAircraftTypeMonthExperience_Activity");
                entity.HasOne(d => d.AircraftTypeGroup)
                    .WithMany(p => p.PersonAircraftTypeMonthExperiences)
                    .HasForeignKey(d => d.AircraftTypeGroupId)
                    .HasConstraintName("FK_PersonAircraftTypeMonthExperience_AircraftTypeGroup");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonAircraftTypeMonthExperiences)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonAircraftTypeMonthExperience_Person");
            });
            modelBuilder.Entity<PersonAircraftTypeRange>(entity =>
            {
                entity.HasKey(e => new { e.PersonId, e.DateFrom, e.AircraftTypeId, e.ActivityId });
                entity.Property(e => e.PersonId).ValueGeneratedNever();
                entity.Property(e => e.DateFrom).ValueGeneratedNever();
                entity.Property(e => e.AircraftTypeId).ValueGeneratedNever();
                entity.Property(e => e.ActivityId).ValueGeneratedNever();
            });
            modelBuilder.Entity<PersonAircraftTypeRangeAggregate>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.AircraftTypeGroups).IsUnicode(false);
                entity.Property(e => e.AircraftTypes).IsUnicode(false);
            });
            modelBuilder.Entity<PersonAirportAfterLifusMonthExperience>(entity =>
            {
                entity.HasKey(e => new { e.PersonId, e.Year, e.Month });
                entity.Property(e => e.Year).ValueGeneratedNever();
                entity.Property(e => e.Month).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonAirportAfterLifusMonthExperiences)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonAirportAfterLifusMonthExperience_Person");
            });
            modelBuilder.Entity<PersonCapacityLicenseGroupRange>(entity =>
            {
                entity.HasKey(e => new { e.Type, e.DateFrom, e.PersonId, e.LicenseGroupId });
                entity.Property(e => e.Type).ValueGeneratedNever();
                entity.Property(e => e.DateFrom).ValueGeneratedNever();
                entity.Property(e => e.PersonId).ValueGeneratedNever();
                entity.Property(e => e.LicenseGroupId).ValueGeneratedNever();
            });
            modelBuilder.Entity<PersonCheckerTrainee>(entity =>
            {
                entity.HasKey(e => new { e.PersonId, e.AircraftTypeGroupId, e.ActivityId, e.CheckerTraineeFunction });
                entity.Property(e => e.CheckerTraineeFunction).ValueGeneratedNever();
                entity.HasOne(d => d.Activity)
                    .WithMany(p => p.PersonCheckerTrainees)
                    .HasForeignKey(d => d.ActivityId)
                    .HasConstraintName("FK_PersonCheckerTrainee_Activity");
                entity.HasOne(d => d.AircraftTypeGroup)
                    .WithMany(p => p.PersonCheckerTrainees)
                    .HasForeignKey(d => d.AircraftTypeGroupId)
                    .HasConstraintName("FK_PersonCheckerTrainee_AircraftTypeGroup");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonCheckerTrainees)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonCheckerTrainee_Person");
            });
            modelBuilder.Entity<PersonContract>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonContracts)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonContract_Person");
            });
            modelBuilder.Entity<PersonDay>(entity =>
            {
                entity.HasKey(e => new { e.IsHistorized, e.Date, e.PersonId });
                entity.Property(e => e.IsHistorized).ValueGeneratedNever();
                entity.Property(e => e.Date).ValueGeneratedNever();
                entity.Property(e => e.CustomTitle).IsUnicode(false);
                entity.Property(e => e.DooType).HasDefaultValueSql("((0))");
                entity.Property(e => e.IsValid).HasComputedColumnSql("(isnull(CONVERT([bit],(((([HasFtlErrors]|[HasGavErrors])|[HasEasaErrors])|[HasAgreementErrors])|[HasOtherErrors])^(1)),CONVERT([bit],(1))))");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonDays)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonDay_Person");
                entity.HasOne(d => d.PersonDateModifiedBy)
                    .WithMany(p => p.PersonDateModifiedBys)
                    .HasForeignKey(d => d.ModifiedByPrincipalId)
                    .HasConstraintName("FK_PersonDay_Principal_PersonDateModifiedBy");
            });
            modelBuilder.Entity<PersonDayAggregatedDuty>(entity =>
            {
                entity.HasKey(e => new { e.IsHistorized, e.PersonId, e.Date });
                entity.Property(e => e.IsHistorized).ValueGeneratedNever();
                entity.Property(e => e.PersonId).ValueGeneratedNever();
                entity.Property(e => e.Date).ValueGeneratedNever();
                entity.Property(e => e.AircraftTypeGroups).IsUnicode(false);
                entity.Property(e => e.CheckerTrainee).IsUnicode(false);
                entity.Property(e => e.CurrentLocation).IsUnicode(false);
                entity.Property(e => e.CurrentLocationDepartureRouteCode).IsUnicode(false);
                entity.Property(e => e.CurrentLocationRouteCode).IsUnicode(false);
                entity.Property(e => e.CurrentLocationTimeDiffToLt).IsUnicode(false);
                entity.Property(e => e.DutyAsText).IsUnicode(false);
                entity.Property(e => e.DutyAsTextShort).IsUnicode(false);
                entity.Property(e => e.RouteActivities).IsUnicode(false);
                entity.Property(e => e.Routing).IsUnicode(false);
                entity.HasOne(d => d.RotationFirstFlight)
                    .WithMany(p => p.RotationFirstPersonDayAggregatedDuties)
                    .HasForeignKey(d => d.RotationFirstFlightId)
                    .HasConstraintName("FK_PersonDayAggregatedDuty_RotationFirstFlight");
            });
            modelBuilder.Entity<PersonDayChange>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.IsConfirmedByPlanningTeam).HasDefaultValueSql("((0))");
                entity.Property(e => e.Reason).IsUnicode(false);
                entity.HasOne(d => d.AlertType)
                    .WithMany(p => p.PersonDayChanges)
                    .HasForeignKey(d => d.AlertTypeId)
                    .HasConstraintName("FK_PersonDayChange_AlertType");
                entity.HasOne(d => d.ConfirmedByPrincipal)
                    .WithMany(p => p.ConfirmedByPersonDayChanges)
                    .HasForeignKey(d => d.ConfirmedByPrincipalId)
                    .HasConstraintName("FK_PersonDayChange_ConfirmedByPrincipal");
                entity.HasOne(d => d.ModifiedByPrincipal)
                    .WithMany(p => p.ModifiedByPersonDayChanges)
                    .HasForeignKey(d => d.ModifiedByPrincipalId)
                    .HasConstraintName("FK_PersonDayChange_ModifiedByPrincipal");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonDayChanges)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonDayChange_Person");
                entity.HasOne(d => d.PersonDayChangeCreatedBy)
                    .WithMany(p => p.PersonDayChangeCreatedBys)
                    .HasForeignKey(d => d.CreatedByPrincipalId)
                    .HasConstraintName("FK_PersonDayChange_Principal_PersonDayChangeCreatedBy");
            });
            modelBuilder.Entity<PersonDayLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonDayLogs)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonDayLog_Person");
                entity.HasOne(d => d.PersonDayLogModifiedBy)
                    .WithMany(p => p.PersonDayLogModifiedBys)
                    .HasForeignKey(d => d.ModifiedByPrincipalId)
                    .HasConstraintName("FK_PersonDayLog_Principal_PersonDayLogModifiedBy");
            });
            modelBuilder.Entity<PersonDayQueue>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonDayQueues)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonDayQueue_Person");
            });
            modelBuilder.Entity<PersonDayQueuePostponeRange>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
            });
            modelBuilder.Entity<PersonDayShadowDuty>(entity =>
            {
                entity.HasKey(e => new { e.Date, e.PersonId });
                entity.Property(e => e.Date).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonDayShadowDuties)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonDayShadowDuty_Person");
            });
            modelBuilder.Entity<PersonDestinationRestriction>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.AirportFourLetterCode).IsUnicode(false);
                entity.HasOne(d => d.Airport)
                    .WithMany(p => p.PersonDestinationRestrictions)
                    .HasForeignKey(d => d.AirportFourLetterCode)
                    .HasConstraintName("FK_PersonDestinationRestriction_Airport");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonDestinationRestrictions)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonDestinationRestriction_Person");
            });
            modelBuilder.Entity<PersonDutySwap>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
            });
            modelBuilder.Entity<PersonEntry>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonEntries)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonEntry_Person");
            });
            modelBuilder.Entity<PersonExperience>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Experience)
                    .WithMany(p => p.PersonExperiences)
                    .HasForeignKey(d => d.ExperienceId)
                    .HasConstraintName("FK_PersonExperience_Experience");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonExperiences)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonExperience_Person");
            });
            modelBuilder.Entity<PersonFigureCacheDay>(entity =>
            {
                entity.HasKey(e => new { e.Date, e.PersonId });
                entity.Property(e => e.Date).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonFigureCacheDays)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonFigureCacheDay_Person");
            });
            modelBuilder.Entity<PersonFigureCacheMonth>(entity =>
            {
                entity.HasKey(e => new { e.IsHistorized, e.Date, e.PersonId });
                entity.Property(e => e.IsHistorized).ValueGeneratedNever();
                entity.Property(e => e.Date).ValueGeneratedNever();
                entity.Property(e => e.BlockHours1MonthLimit).HasDefaultValueSql("((0))");
                entity.Property(e => e.FreeOfDutyConsecutive3MDays).HasDefaultValueSql("((0))");
                entity.Property(e => e.FreeOfDutyConsecutive3MDaysMinRequired).HasDefaultValueSql("((0))");
                entity.Property(e => e.FreeOfDutyDays).HasDefaultValueSql("((0))");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonFigureCacheMonths)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonFigureCacheMonth_Person");
            });
            modelBuilder.Entity<PersonFigureCacheQuarter>(entity =>
            {
                entity.HasKey(e => new { e.IsHistorized, e.Year, e.Quarter, e.PersonId });
                entity.Property(e => e.IsHistorized).ValueGeneratedNever();
                entity.Property(e => e.Year).ValueGeneratedNever();
                entity.Property(e => e.Quarter).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonFigureCacheQuarters)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonFigureCacheQuarter_Person");
            });
            modelBuilder.Entity<PersonFigureCacheYear>(entity =>
            {
                entity.HasKey(e => new { e.Year, e.PersonId });
                entity.Property(e => e.Year).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonFigureCacheYears)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonFigureCacheYear_Person");
            });
            modelBuilder.Entity<PersonFleet>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonFleets)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonFleet_Person");
            });
            modelBuilder.Entity<PersonFunction>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.AircraftTypeGroup)
                    .WithMany(p => p.PersonFunctions)
                    .HasForeignKey(d => d.NewcomerAircraftTypeGroupId)
                    .HasConstraintName("FK_PersonFunction_AircraftTypeGroup");
                entity.HasOne(d => d.Function)
                    .WithMany(p => p.PersonFunctions)
                    .HasForeignKey(d => d.FunctionId)
                    .HasConstraintName("FK_PersonFunction_Function");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonFunctions)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonFunction_Person");
            });
            modelBuilder.Entity<PersonLicense>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.HardDateTo).HasComputedColumnSql("(case when [ExtendedExpirationDate] IS NULL then [ExpirationDate] else case when [ExtendedExpirationDate]&gt;[ExpirationDate] OR [ExpirationDate] IS NULL then [ExtendedExpirationDate] else [ExpirationDate] end end)");
                entity.HasOne(d => d.License)
                    .WithMany(p => p.PersonLicenses)
                    .HasForeignKey(d => d.LicenseId)
                    .HasConstraintName("FK_PersonLicense_License");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonLicenses)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonLicense_Person");
            });
            modelBuilder.Entity<PersonLicenseBack>(entity =>
            {
                entity.HasKey(e => new { e.Id, e.PersonId, e.LicenseId, e.IsTrainee, e.IsNewcomer, });
            });
            modelBuilder.Entity<PersonPlaningAutonomy>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonPlaningAutonomies)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonPlaningAutonomy_PersonId");
            });
            modelBuilder.Entity<PersonPointLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.ActivityRcd).IsUnicode(false);
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonPointLogs)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonPointLog_Person");
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.PersonPointLogs)
                    .HasForeignKey(d => d.PrincipalId)
                    .HasConstraintName("FK_PersonPointLog_Principal");
            });
            modelBuilder.Entity<PersonRelative>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonRelatives)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonRelative_Person");
            });
            modelBuilder.Entity<PersonRequestFlight>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.Date).HasComputedColumnSql("(isnull(datefromparts((2000)+CONVERT([smallint],CONVERT([varbinary](1),[FlightId])),CONVERT([int],substring(CONVERT([varbinary](3),[FlightId]),(2),(1))),CONVERT([int],substring(CONVERT([varbinary](3),[FlightId]),(3),(1)))),datefromparts((2000),(1),(1))))");
                entity.HasOne(d => d.Flight)
                    .WithMany(p => p.PersonRequestFlights)
                    .HasForeignKey(d => d.FlightId)
                    .HasConstraintName("FK_PersonRequestFlight_Flight");
                entity.HasOne(d => d.Function)
                    .WithMany(p => p.PersonRequestFlights)
                    .HasForeignKey(d => d.FunctionId)
                    .HasConstraintName("FK_PersonRequestFlight_Function");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonRequestFlights)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonRequestFlight_Person");
                entity.HasOne(d => d.RequestedByPrincipal)
                    .WithMany(p => p.RequestedByPersonRequestFlights)
                    .HasForeignKey(d => d.RequestedByPrincipalId)
                    .HasConstraintName("FK_PersonRequestFlight_RequestedByPrincipal");
            });
            modelBuilder.Entity<PersonRequestFlightLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.ChangedByPrincipal)
                    .WithMany(p => p.ChangedByPersonRequestFlightLogs)
                    .HasForeignKey(d => d.ChangedByPrincipalId)
                    .HasConstraintName("FK_PersonRequestFlightLog_ChangedByPrincipal");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonRequestFlightLogs)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonRequestFlightLog_Person");
                entity.HasOne(d => d.Request)
                    .WithMany(p => p.Requests)
                    .HasForeignKey(d => d.RequestId)
                    .HasConstraintName("FK_PersonRequestFlightLog_Request");
            });
            modelBuilder.Entity<PersonRequestOff>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Operation)
                    .WithMany(p => p.PersonRequestOffs)
                    .HasForeignKey(d => d.OperationId)
                    .HasConstraintName("FK_PersonRequestOff_Operation");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonRequestOffs)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonRequestOff_Person");
                entity.HasOne(d => d.RequestedByPrincipal)
                    .WithMany(p => p.RequestedByPersonRequestOffs)
                    .HasForeignKey(d => d.RequestedByPrincipalId)
                    .HasConstraintName("FK_PersonRequestOff_RequestedByPrincipal");
            });
            modelBuilder.Entity<PersonRequestOffLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.ChangedByPrincipal)
                    .WithMany(p => p.ChangedByPersonRequestOffLogs)
                    .HasForeignKey(d => d.ChangedByPrincipalId)
                    .HasConstraintName("FK_PersonRequestOffLog_ChangedByPrincipal");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonRequestOffLogs)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonRequestOffLog_Person");
                entity.HasOne(d => d.Request)
                    .WithMany(p => p.Requests)
                    .HasForeignKey(d => d.RequestId)
                    .HasConstraintName("FK_PersonRequestOffLog_Request");
            });
            modelBuilder.Entity<PersonRequestRotationDay>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.Title).IsUnicode(false);
                entity.HasOne(d => d.PersonRequestFlight)
                    .WithMany(p => p.PersonRequestRotationDays)
                    .HasForeignKey(d => d.RequestId)
                    .HasConstraintName("FK_PersonRequestRotationDay_PersonRequestFlight");
            });
            modelBuilder.Entity<PersonRequestVac>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.ApprovedByPrincipal)
                    .WithMany(p => p.ApprovedByPersonRequestVacs)
                    .HasForeignKey(d => d.ApprovedByPrincipalId)
                    .HasConstraintName("FK_PersonRequestVac_ApprovedByPrincipal");
                entity.HasOne(d => d.PersonRequestVacBlock)
                    .WithMany(p => p.PersonRequestVacs)
                    .HasForeignKey(d => d.RequestBlockId)
                    .HasConstraintName("FK_PersonRequestVac_PersonRequestVacBlock");
                entity.HasOne(d => d.RequestedByPrincipal)
                    .WithMany(p => p.RequestedByPersonRequestVacs)
                    .HasForeignKey(d => d.RequestedByPrincipalId)
                    .HasConstraintName("FK_PersonRequestVac_RequestedByPrincipal");
            });
            modelBuilder.Entity<PersonRequestVacBlock>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonRequestVacBlocks)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonRequestVacBlock_Person");
                entity.HasOne(d => d.VacationYear)
                    .WithMany(p => p.PersonRequestVacBlocks)
                    .HasForeignKey(d => d.VacationYearId)
                    .HasConstraintName("FK_PersonRequestVacBlock_VacationYear");
                entity.HasOne(d => d.VacationYearPeriod)
                    .WithMany(p => p.PersonRequestVacBlocks)
                    .HasForeignKey(d => d.VacationYearPeriodId)
                    .HasConstraintName("FK_PersonRequestVacBlock_VacationYearPeriod");
            });
            modelBuilder.Entity<PersonRequestVacBlockLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.ChangedByPrincipal)
                    .WithMany(p => p.ChangedByPersonRequestVacBlockLogs)
                    .HasForeignKey(d => d.ChangedByPrincipalId)
                    .HasConstraintName("FK_PersonRequestVacBlockLog_ChangedByPrincipal");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonRequestVacBlockLogs)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonRequestVacBlockLog_Person");
                entity.HasOne(d => d.PersonRequestVacBlock)
                    .WithMany(p => p.PersonRequestVacBlockLogs)
                    .HasForeignKey(d => d.RequestBlockId)
                    .HasConstraintName("FK_PersonRequestVacBlockLog_PersonRequestVacBlock");
                entity.HasOne(d => d.VacationYear)
                    .WithMany(p => p.PersonRequestVacBlockLogs)
                    .HasForeignKey(d => d.VacationYearId)
                    .HasConstraintName("FK_PersonRequestVacBlockLog_VacationYear");
                entity.HasOne(d => d.VacationYearPeriod)
                    .WithMany(p => p.PersonRequestVacBlockLogs)
                    .HasForeignKey(d => d.VacationYearPeriodId)
                    .HasConstraintName("FK_PersonRequestVacBlockLog_VacationYearPeriod");
            });
            modelBuilder.Entity<PersonRequestVacDutyPriorityPointsCache>(entity =>
            {
                entity.HasKey(e => new { e.PersonId, e.DateFrom, e.DateTo });
                entity.Property(e => e.PersonId).ValueGeneratedNever();
                entity.Property(e => e.DateFrom).ValueGeneratedNever();
                entity.Property(e => e.DateTo).ValueGeneratedNever();
            });
            modelBuilder.Entity<PersonRequestVacLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.ChangedByPrincipal)
                    .WithMany(p => p.ChangedByPersonRequestVacLogs)
                    .HasForeignKey(d => d.ChangedByPrincipalId)
                    .HasConstraintName("FK_PersonRequestVacLog_ChangedByPrincipal");
                entity.HasOne(d => d.PersonRequestVac)
                    .WithMany(p => p.PersonRequestVacLogs)
                    .HasForeignKey(d => d.VacRequestId)
                    .HasConstraintName("FK_PersonRequestVacLog_PersonRequestVac");
                entity.HasOne(d => d.PersonRequestVacBlock)
                    .WithMany(p => p.PersonRequestVacLogs)
                    .HasForeignKey(d => d.RequestBlockId)
                    .HasConstraintName("FK_PersonRequestVacLog_PersonRequestVacBlock");
            });
            modelBuilder.Entity<PersonRequestVacPriorityPointsAggregateCache>(entity =>
            {
                entity.HasKey(e => new { e.RequestBlockId, e.PersonId });
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonRequestVacPriorityPointsAggregateCaches)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonRequestVacPriorityPointsAggregateCache_PersonId");
                entity.HasOne(d => d.RequestBlock)
                    .WithMany(p => p.RequestBlocks)
                    .HasForeignKey(d => d.RequestBlockId)
                    .HasConstraintName("FK_PersonRequestVacPriorityPointsAggregateCache_RequestBlockId");
            });
            modelBuilder.Entity<PersonRevalidate>(entity =>
            {
                entity.Property(e => e.ChangeDays).IsUnicode(false);
                entity.Property(e => e.ChangedFlightIds).IsUnicode(false);
                entity.Property(e => e.ChangeLogDays).IsUnicode(false);
                entity.Property(e => e.OperationIds).IsUnicode(false);
                entity.HasOne(d => d.Person)
                    .WithOne(p => p.PersonRevalidate)
                    .HasForeignKey<PersonRevalidate>(d => d.PersonId)
                    .HasConstraintName("FK_PersonRevalidate_Person");
            });
            modelBuilder.Entity<PersonRevalidateDutyChange>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Activity)
                    .WithMany(p => p.PersonRevalidateDutyChanges)
                    .HasForeignKey(d => d.ActivityId)
                    .HasConstraintName("FK_PersonRevalidateDutyChange_Activity");
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonRevalidateDutyChanges)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonRevalidateDutyChange_Person");
            });
            modelBuilder.Entity<PersonSetting>(entity =>
            {
                entity.HasOne(d => d.Person)
                    .WithOne(p => p.PersonSetting)
                    .HasForeignKey<PersonSetting>(d => d.PersonId)
                    .HasConstraintName("FK_PersonSetting_Person");
            });
            modelBuilder.Entity<PersonTzvLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.ActivityRcd).IsUnicode(false);
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonTzvLogs)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonTzvLog_Person");
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.PersonTzvLogs)
                    .HasForeignKey(d => d.PrincipalId)
                    .HasConstraintName("FK_PersonTzvLog_Principal");
                entity.HasOne(d => d.TzvYear)
                    .WithMany(p => p.PersonTzvLogs)
                    .HasForeignKey(d => d.TzvYearId)
                    .HasConstraintName("FK_PersonTzvLog_TzvYear");
            });
            modelBuilder.Entity<PersonVacationLog>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.ActivityRcd).IsUnicode(false);
                entity.HasOne(d => d.Person)
                    .WithMany(p => p.PersonVacationLogs)
                    .HasForeignKey(d => d.PersonId)
                    .HasConstraintName("FK_PersonVacationLog_Person");
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.PersonVacationLogs)
                    .HasForeignKey(d => d.PrincipalId)
                    .HasConstraintName("FK_PersonVacationLog_Principal");
                entity.HasOne(d => d.VacationYear)
                    .WithMany(p => p.PersonVacationLogs)
                    .HasForeignKey(d => d.VacationYearId)
                    .HasConstraintName("FK_PersonVacationLog_VacationYear");
            });
            modelBuilder.Entity<Positioning>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.DestinationRcd).IsUnicode(false);
                entity.Property(e => e.OriginRcd).IsUnicode(false);
                entity.HasOne(d => d.Flight)
                    .WithMany(p => p.Positionings)
                    .HasForeignKey(d => d.FlightId)
                    .HasConstraintName("FK_Positioning_Flight");
            });
            modelBuilder.Entity<Principal>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
            });
            modelBuilder.Entity<PrincipalConfiguration>(entity =>
            {
                entity.HasKey(e => new { e.PrincipalId, e.Group, e.Key });
                entity.Property(e => e.Group).IsUnicode(false);
                entity.Property(e => e.Key).IsUnicode(false);
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.PrincipalConfigurations)
                    .HasForeignKey(d => d.PrincipalId)
                    .HasConstraintName("FK_PrincipalConfiguration_Principal");
            });
            modelBuilder.Entity<PushNotificationSubscription>(entity =>
            {
                entity.HasKey(e => new { e.PrincipalId, e.Endpoint });
                entity.Property(e => e.Endpoint).IsUnicode(false);
                entity.Property(e => e.Auth).IsUnicode(false);
                entity.Property(e => e.P256Dh).IsUnicode(false);
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.PushNotificationSubscriptions)
                    .HasForeignKey(d => d.PrincipalId)
                    .HasConstraintName("FK_PushNotificationSubscription_Principal");
            });
            modelBuilder.Entity<PushNotificationSubscriptionMobile>(entity =>
            {
                entity.HasKey(e => new { e.PushToken, e.PrincipalId });
                entity.Property(e => e.PushToken).IsUnicode(false);
                entity.Property(e => e.Timestamp).HasDefaultValueSql("(getdate())");
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.PushNotificationSubscriptionMobiles)
                    .HasForeignKey(d => d.PrincipalId)
                    .HasConstraintName("FK_PushNotificationSubscriptionMobile_Principal");
            });
            modelBuilder.Entity<ReleaseHistory>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.FunctionGroup)
                    .WithMany(p => p.ReleaseHistories)
                    .HasForeignKey(d => d.FunctionGroupId)
                    .HasConstraintName("FK_ReleaseHistory_FunctionGroup");
                entity.HasOne(d => d.ReleaseHistoryModifiedBy)
                    .WithMany(p => p.ReleaseHistoryModifiedBys)
                    .HasForeignKey(d => d.ModifiedByPrincipalId)
                    .HasConstraintName("FK_ReleaseHistory_Principal_ReleaseHistoryModifiedBy");
            });
            modelBuilder.Entity<RequestCapacity>(entity =>
            {
                entity.HasKey(e => new { e.Type, e.Date, e.FunctionId, e.CapacityLicenseGroupId });
                entity.Property(e => e.Type).ValueGeneratedNever();
                entity.Property(e => e.Date).ValueGeneratedNever();
                entity.HasOne(d => d.CapacityLicenseGroup)
                    .WithMany(p => p.CapacityRequestCapacities)
                    .HasForeignKey(d => d.CapacityLicenseGroupId)
                    .HasConstraintName("FK_RequestCapacity_CapacityLicenseGroup");
                entity.HasOne(d => d.Function)
                    .WithMany(p => p.RequestCapacities)
                    .HasForeignKey(d => d.FunctionId)
                    .HasConstraintName("FK_RequestCapacity_Function");
            });
            modelBuilder.Entity<RequestCapacityLicenseDistribution>(entity =>
            {
                entity.HasKey(e => new { e.Date, e.FunctionId, e.PersonLicenseGroupId, e.CapacityLicenseGroupId });
                entity.Property(e => e.Date).ValueGeneratedNever();
                entity.HasOne(d => d.CapacityLicenseGroup)
                    .WithMany(p => p.CapacityRequestCapacityLicenseDistributions)
                    .HasForeignKey(d => d.CapacityLicenseGroupId)
                    .HasConstraintName("FK_RequestCapacityLicenseDistribution_CapacityLicenseGroup");
                entity.HasOne(d => d.Function)
                    .WithMany(p => p.RequestCapacityLicenseDistributions)
                    .HasForeignKey(d => d.FunctionId)
                    .HasConstraintName("FK_RequestCapacityLicenseDistribution_Function");
                entity.HasOne(d => d.PersonLicenseGroup)
                    .WithMany(p => p.PersonRequestCapacityLicenseDistributions)
                    .HasForeignKey(d => d.PersonLicenseGroupId)
                    .HasConstraintName("FK_RequestCapacityLicenseDistribution_PersonLicenseGroup");
            });
            modelBuilder.Entity<RestFacility>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.Name).IsUnicode(false);
            });
            modelBuilder.Entity<RosterImport>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Principal)
                    .WithMany(p => p.RosterImports)
                    .HasForeignKey(d => d.PrincipalId)
                    .HasConstraintName("FK_RosterImport_Principal");
            });
            modelBuilder.Entity<Rotation>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.Direction).IsUnicode(false);
                entity.Property(e => e.DurationInDays).HasComputedColumnSql("(case when [PeriodFrom]=[PeriodTo] AND [Type]=(1) then (1) else datediff(day,[RotationStartDutyUtc],[RotationEndDutyUtc])+(1) end)");
                entity.Property(e => e.Name).IsUnicode(false);
                entity.Property(e => e.RotationEndDutyDiffToLt).IsUnicode(false);
                entity.Property(e => e.RotationStartDutyDiffToLt).IsUnicode(false);
                entity.Property(e => e.Routing).IsUnicode(false);
                entity.Property(e => e.Type).HasDefaultValueSql("((0))");
            });
            modelBuilder.Entity<RotationCrewComplements>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.HasOne(d => d.Rotation)
                    .WithMany(p => p.RotationCrewComplements)
                    .HasForeignKey(d => d.RotationId)
                    .HasConstraintName("FK_RotationCrewComplements_Rotation");
            });
            modelBuilder.Entity<RotationDuty>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.ActivityRcd).IsUnicode(false);
                entity.Property(e => e.AirlineRcd).IsUnicode(false);
                entity.Property(e => e.ArrivalDiffToLt).IsUnicode(false);
                entity.Property(e => e.ArrivalRcd).IsUnicode(false);
                entity.Property(e => e.DepartureDiffToLt).IsUnicode(false);
                entity.Property(e => e.DepartureRcd).IsUnicode(false);
                entity.Property(e => e.InFlightRestTime).IsUnicode(false);
                entity.HasOne(d => d.Flight)
                    .WithMany(p => p.RotationDuties)
                    .HasForeignKey(d => d.FlightId)
                    .HasConstraintName("FK_RotationDuty_Flight");
                entity.HasOne(d => d.Rotation)
                    .WithMany(p => p.RotationDuties)
                    .HasForeignKey(d => d.RotationId)
                    .HasConstraintName("FK_RotationDuty_Rotation");
            });
            modelBuilder.Entity<ServiceBusMessage>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.Label).IsUnicode(false);
            });
            modelBuilder.Entity<Simulation>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.SimulationType).HasDefaultValueSql("((0))");
            });
            modelBuilder.Entity<StatisticsMessage>(entity =>
            {
                entity.Property(e => e.DateTime).ValueGeneratedNever();
            });
            modelBuilder.Entity<TzvYear>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.CodeName).IsUnicode(false);
            });
            modelBuilder.Entity<VacationYear>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.CodeName).IsUnicode(false);
            });
            modelBuilder.Entity<VacationYearPeriod>(entity =>
            {
                entity.Property(e => e.Id).ValueGeneratedNever();
                entity.Property(e => e.CodeName).IsUnicode(false);
                entity.HasOne(d => d.VacationYear)
                    .WithMany(p => p.VacationYearPeriods)
                    .HasForeignKey(d => d.VacationYearId)
                    .HasConstraintName("FK_VacationYearPeriod_VacationYear");
            });
            modelBuilder.Entity<vBlockCalculationQueueNextItem>(entity =>
            {
                entity.HasKey(e => new { e.Type, e.Id, e.RowNumber });
            });
            modelBuilder.Entity<vCapacityStats>(entity =>
            {
                entity.HasKey(e => new { e.Type, e.Date, e.FunctionId, e.CapacityLicenseGroupId, e.DailyCapacityUsed,  });
            });
            modelBuilder.Entity<vLongHaulOffReport>(entity =>
            {
                entity.HasKey(e => new { e.ActivityCodeName, e.Date, e.DutyId, e.PersonId, e.IsAfterNightDuty, e.IsBeforeNightDuty });
                entity.Property(e => e.ActivityCodeName).IsUnicode(false);
            });
            modelBuilder.Entity<vPersonAircraftTypeGroupRecencyReport>(entity =>
            {
                entity.HasKey(e => new { e.Code, e.Contract, e.Function, e.AircraftType,  });
                entity.Property(e => e.AircraftType).IsUnicode(false);
                entity.Property(e => e.Code).IsUnicode(false);
                entity.Property(e => e.Contract).IsUnicode(false);
                entity.Property(e => e.Function).IsUnicode(false);
            });
            modelBuilder.Entity<vPersonCapacity>(entity =>
            {
                entity.HasKey(e => new { e.PersonId, e.PersonCode, e.Type, e.Date, e.FunctionName, e.CapacityLicenseGroupId, e.PersonLicenseGroupId, e.DailyCapacityUsed, e.PersonRequestedValue, e.HasDayCapacity, e.HasMonthCapacity });
                entity.Property(e => e.FunctionName).IsUnicode(false);
                entity.Property(e => e.PersonCode).IsUnicode(false);
            });
            modelBuilder.Entity<vPersonCapacityLicense>(entity =>
            {
                entity.HasKey(e => new { e.Type, e.Date, e.PersonId, e.LicenseId, e.LicenseIdId });
            });
            modelBuilder.Entity<vPersonCapacityPerDay>(entity =>
            {
                entity.HasKey(e => new { e.Type, e.PersonId, e.Date, e.HasDayCapacity, e.HasMonthCapacity });
            });
            modelBuilder.Entity<vPersonDayQueueNextItem>(entity =>
            {
                entity.HasKey(e => new { e.Id,  });
            });
            modelBuilder.Entity<vPersonRequestFlightNotDeleted>(entity =>
            {
                entity.HasKey(e => new { e.FlightId, e.FunctionId,  });
                entity.Property(e => e.Bids).IsUnicode(false);
            });
            modelBuilder.Entity<vPersonRequestFlightRequested>(entity =>
            {
                entity.HasKey(e => new { e.FlightId, e.FunctionId,  });
                entity.Property(e => e.Bids).IsUnicode(false);
            });
            modelBuilder.Entity<vPersonRequestVacFunctionContract>(entity =>
            {
                entity.HasKey(e => new { e.RequestBlockId, e.Rank, e.Has320AircraftType, e.Has330AircraftType, e.Has340AircraftType });
                entity.Property(e => e.FunctionName).IsUnicode(false);
                entity.Property(e => e.PersonAircrafts).IsUnicode(false);
            });
            modelBuilder.Entity<vPersonRequestVacPriorityPoints>(entity =>
            {
                entity.HasKey(e => new { e.Type, e.PersonId, e.Id, e.RequestBlockId, e.Timestamp, e.RequestedByPrincipalId, e.Priority, e.Status, e.PeriodFrom, e.PeriodTo, e.Days, e.SelectedDateFrom, e.SelectedDateTo, e.IsDeleted, e.Category, e.RequestBlockVacationPeriodDateFrom, e.RequestBlockVacationPeriodDateTo,  });
            });
            modelBuilder.Entity<vPersonRequestVacPriorityPointsAggregate>(entity =>
            {
                entity.HasKey(e => new { e.RequestBlockId, e.PersonId, e.VacPPriorityPoints, e.VacSPriorityPoints, e.VacNPriorityPoints });
            });
            modelBuilder.Entity<vPersonRequestVacVariants>(entity =>
            {
                entity.HasKey(e => new { e.Id, e.VariantHighPrioId, e.VariantHighPrioPeriodFrom, e.VariantHighPrioPeriodTo, e.VariantHighPrioDays, e.VariantHighPrioTimestamp, e.VariantHighPrioStatus, e.MinRequestDate, e.MaxRequestDate });
            });
            modelBuilder.Entity<vPersonSeniorityRank>(entity =>
            {
                entity.HasKey(e => new { e.PersonId, e.Rank });
            });
            modelBuilder.Entity<vPersonTzvYearOverview>(entity =>
            {
                entity.HasKey(e => new { e.FunctionGroupName, e.FunctionGroupId, e.FunctionName, e.FunctionId, e.ContractType, e.ContractTypeModel, e.TzvYearId, e.PersonId, e.BalanceActualYear, e.Available, e.BacklogCurrent, e.BacklogPreviousYear, e.Confirmed, e.ConfirmedJan, e.ConfirmedFeb, e.ConfirmedMar, e.ConfirmedApr, e.ConfirmedMay, e.ConfirmedJun, e.ConfirmedJul, e.ConfirmedAug, e.ConfirmedSep, e.ConfirmedOct, e.ConfirmedNov, e.ConfirmedDec });
                entity.Property(e => e.FunctionName).IsUnicode(false);
            });
            modelBuilder.Entity<vPersonVacYearDetails>(entity =>
            {
                entity.HasKey(e => new { e.FunctionGroupName, e.FunctionGroupId, e.FunctionName, e.FunctionId, e.ContractType, e.ContractTypeModel, e.PersonId, e.VacationYearId, e.Cabin14DaysRule, e.Cabin1HalfDaysCount, e.CabinHalfYearRule, e.Cabin2HalfDaysCount, e.CockpitCanTake14VacP, e.CockpitHas14VacPThisYear, e.CockpitCanTake21VacP, e.CockpitHas21VacPThisYear, e.CockpitHasVacS });
                entity.Property(e => e.FunctionName).IsUnicode(false);
            });
            modelBuilder.Entity<vRotationCrewFunctionComplements>(entity =>
            {
                entity.HasKey(e => new { e.FunctionId, e.RotationId, e.Count, e.Date });
            });
            modelBuilder.Entity<vTzvDaysBalance>(entity =>
            {
                entity.HasKey(e => new { e.TzvYearId, e.PersonId, e.BalanceActualYear, e.Available, e.BacklogCurrent, e.BacklogPreviousYear, e.Confirmed, e.ConfirmedJan, e.ConfirmedFeb, e.ConfirmedMar, e.ConfirmedApr, e.ConfirmedMay, e.ConfirmedJun, e.ConfirmedJul, e.ConfirmedAug, e.ConfirmedSep, e.ConfirmedOct, e.ConfirmedNov, e.ConfirmedDec });
            });
            modelBuilder.Entity<vUsedCapacity>(entity =>
            {
                entity.HasKey(e => new { e.Date, e.Code, e.Id, e.Value, e.CapacityLicenseGroupId, e.PersonLicenseGroupId, e.FunctionId, e.Name, e.Type });
                entity.Property(e => e.Code).IsUnicode(false);
                entity.Property(e => e.Name).IsUnicode(false);
            });
            modelBuilder.Entity<vUsedCapacityVacRequest>(entity =>
            {
                entity.HasKey(e => new { e.Date, e.Code, e.PersonId, e.Value, e.CapacityLicenseGroupId, e.PersonLicenseGroupId, e.FunctionId, e.Name, e.Type,  });
                entity.Property(e => e.Code).IsUnicode(false);
                entity.Property(e => e.Name).IsUnicode(false);
            });
            modelBuilder.Entity<vVacationDaysBalance>(entity =>
            {
                entity.HasKey(e => new { e.VacationYearId, e.PersonId, e.BalanceActualYear, e.Confirmed, e.PreviousVacationYearBalance, e.GrantedByContract });
            });
            modelBuilder.Entity<vVacationPendingRequest>(entity =>
            {
                entity.HasKey(e => new { e.VacationYearId, e.PersonId, e.PendingConfirmed });
            });
            modelBuilder.Entity<vVacationsOffReport>(entity =>
            {
                entity.HasKey(e => new { e.ActivityCodeName, e.Date, e.DutyId, e.PersonId, e.VacationDate,  });
                entity.Property(e => e.ActivityCodeName).IsUnicode(false);
            });
            modelBuilder.Entity<vValidationItems>(entity =>
            {
                entity.HasKey(e => new { e.Id, e.Date, e.PersonId, e.IsHistorized, e.DutyTimeSec, e.BlockTimeSec, e.Title, e.ActivityRcd, e.PilotsCount, e.MedicalRestrictionPersonsCount, e.AgeRulePersonsCount, e.InexperiencedPersonsCount, e.Landing320Count, e.Landing330Count, e.Landing340Count, e.LandingFNCCount });
                entity.Property(e => e.ActivityRcd).IsUnicode(false);
                entity.Property(e => e.AircraftTypeGroupName).IsUnicode(false);
                entity.Property(e => e.AirlineRcd).IsUnicode(false);
                entity.Property(e => e.AirportThreeLettersCode).IsUnicode(false);
                entity.Property(e => e.DateFromDiffString).IsUnicode(false);
                entity.Property(e => e.DateToDiffString).IsUnicode(false);
                entity.Property(e => e.DestinationRcd).IsUnicode(false);
                entity.Property(e => e.OriginRcd).IsUnicode(false);
            });
        }

Let me know if you need anything else, happy to help.
Thanks!

@maumar
Copy link
Contributor

maumar commented Feb 18, 2020

@yahorsi thanks for the additional info, I'm able to reproduce it now

@maumar
Copy link
Contributor

maumar commented Feb 18, 2020

simplified repro:

        [ConditionalFact]
        public virtual void Repro19825()
        {
            using var ctx = new Context19825();
            ctx.Database.EnsureDeleted();
            ctx.Database.EnsureCreated();

            var fails = from r in ctx.Rotations
                        join rd in ctx.RotationDuties on r.Id equals rd.RotationId
                        join f in ctx.Flights on rd.FlightId equals f.Id
                        join d in ctx.Duties on f.Id equals d.FlightId
                        from pe in ctx.PersonExperiences.Where(pe => pe.DateFrom <= rd.Date && (rd.Date <= pe.DateTo || pe.DateTo == null) && pe.PersonId == d.PersonId).DefaultIfEmpty()
                        select 1;

            var works = from rd in ctx.RotationDuties
                        join f in ctx.Flights on rd.FlightId equals f.Id
                        join d in ctx.Duties on f.Id equals d.FlightId
                        from pe in ctx.PersonExperiences.Where(pe => pe.DateFrom <= rd.Date && (rd.Date <= pe.DateTo || pe.DateTo == null) && pe.PersonId == d.PersonId).DefaultIfEmpty()
                        select 1;

            var result = fails.ToList();
            var result2 = works.ToList();
        }

        public class Rotation
        {
            public Guid Id { get; set; }

            [InverseProperty("Rotation")]
            public ICollection<RotationDuty> RotationDuties { get; set; }
        }


        public class RotationDuty
        {

            public Guid Id { get; set; }

            public Guid RotationId { get; set; }

            [Column(TypeName = "date")]
            public DateTime Date { get; set; }

            public Guid? FlightId { get; set; }

            [ForeignKey("FlightId")]
            [InverseProperty("RotationDuties")]
            public Flight Flight { get; set; }
            [ForeignKey("RotationId")]
            [InverseProperty("RotationDuties")]
            public Rotation Rotation { get; set; }
        }


        public class Flight
        {
            public Guid Id { get; set; }

            [InverseProperty("Flight")]
            public ICollection<Duty> Duties { get; set; }
            [InverseProperty("Flight")]
            public ICollection<RotationDuty> RotationDuties { get; set; }
        }


        public class Duty
        {
            public Guid PersonId { get; set; }

            public Guid? FlightId { get; set; }

            public Guid Id { get; set; }

            [ForeignKey("FlightId")]
            [InverseProperty("Duties")]
            public Flight Flight { get; set; }
        }

        public class PersonExperience
        {

            public Guid Id { get; set; }

            public Guid PersonId { get; set; }

            [Column(TypeName = "datetime")]
            public DateTime DateFrom { get; set; }

            [Column(TypeName = "datetime")]
            public DateTime? DateTo { get; set; }
        }


        public class Function
        {
            public Guid Id { get; set; }

            [Required]
            [StringLength(3)]
            public string Name { get; set; }

            public Guid? FunctionGroupId { get; set; }
        }

        public class Context19825 : DbContext
        {
            public DbSet<Rotation> Rotations { get; set; }
            public DbSet<RotationDuty> RotationDuties { get; set; }
            public DbSet<Flight> Flights { get; set; }
            public DbSet<Duty> Duties { get; set; }
            public DbSet<PersonExperience> PersonExperiences { get; set; }
            public DbSet<Function> Functions { get; set; }


            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer(@"Server=.;Database=Repro19825;Trusted_Connection=True;MultipleActiveResultSets=True");
            }
        }

@maumar
Copy link
Contributor

maumar commented Feb 18, 2020

Problem is in SelectExpression.AddJoin - we fail to identify outer references in the innerSelectExpression because we don't match column expression with JoinExpressionBase - we should be looking into the Table of the join instead.

@maumar maumar changed the title Core 3.1, EF 3.1.1, SqlServer, Outer Apply, Invalid SQL, "The multi-part identifier "r0.Date" could not be bound." Query: incorrectly generating JOIN rather than APPLY for subqueries with outside references to a joined table Feb 19, 2020
maumar added a commit that referenced this issue Feb 19, 2020
…for subqueries with outside references to a joined table

During translation, when we decide whether we can apply JOIN or APPLY we visit inner SelectExpression looking for references to tables in the outer SelectExpression.
Problem was that we were using Contains method, which would not match cases where the outer table was in the form of JoinExpressionBase.
Fix is to use ContainsTableReference method which matches different types of tables.
@maumar maumar added closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. Servicing-consider labels Feb 19, 2020
maumar added a commit that referenced this issue Feb 19, 2020
…for subqueries with outside references to a joined table

During translation, when we decide whether we can apply JOIN or APPLY we visit inner SelectExpression looking for references to tables in the outer SelectExpression.
Problem was that we were using Contains method, which would not match cases where the outer table was in the form of JoinExpressionBase.
Fix is to use ContainsTableReference method which matches different types of tables.
maumar added a commit that referenced this issue Feb 19, 2020
…for subqueries with outside references to a joined table

During translation, when we decide whether we can apply JOIN or APPLY we visit inner SelectExpression looking for references to tables in the outer SelectExpression.
Problem was that we were using Contains method, which would not match cases where the outer table was in the form of JoinExpressionBase.
Fix is to use ContainsTableReference method which matches different types of tables.
@maumar
Copy link
Contributor

maumar commented Feb 19, 2020

fixed in fd07ee9

@maumar maumar closed this as completed Feb 19, 2020
maumar added a commit that referenced this issue Feb 20, 2020
…for subqueries with outside references to a joined table

During translation, when we decide whether we can apply JOIN or APPLY we visit inner SelectExpression looking for references to tables in the outer SelectExpression.
Problem was that we were using Contains method, which would not match cases where the outer table was in the form of JoinExpressionBase.
Fix is to use ContainsTableReference method which matches different types of tables.
@maumar maumar reopened this Feb 20, 2020
maumar added a commit that referenced this issue Feb 20, 2020
…for subqueries with outside references to a joined table

During translation, when we decide whether we can apply JOIN or APPLY we visit inner SelectExpression looking for references to tables in the outer SelectExpression.
Problem was that we were using Contains method, which would not match cases where the outer table was in the form of JoinExpressionBase.
Fix is to use ContainsTableReference method which matches different types of tables.
@ajcvickers
Copy link
Member

@maumar to create a 3.1.x PR.

maumar added a commit that referenced this issue Feb 25, 2020
…for subqueries with outside references to a joined table

During translation, when we decide whether we can apply JOIN or APPLY we visit inner SelectExpression looking for references to tables in the outer SelectExpression.
Problem was that we were using Contains method, which would not match cases where the outer table was in the form of JoinExpressionBase.
Fix is to use ContainsTableReference method which matches different types of tables.
@ajcvickers ajcvickers modified the milestones: 3.1.x, 3.1.4 Mar 5, 2020
@smitpatel
Copy link
Member

This has not been merged to release/3.1

@ajcvickers
Copy link
Member

@smitpatel I thought that was happening yesterday. Sorry.

@ajcvickers ajcvickers reopened this Mar 31, 2020
ajcvickers pushed a commit that referenced this issue Apr 4, 2020
…for subqueries with outside references to a joined table

During translation, when we decide whether we can apply JOIN or APPLY we visit inner SelectExpression looking for references to tables in the outer SelectExpression.
Problem was that we were using Contains method, which would not match cases where the outer table was in the form of JoinExpressionBase.
Fix is to use ContainsTableReference method which matches different types of tables.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment