Skip to content

Reverse engineering: Unique Index interpreted incorrectly to give one-to-one instead of one-to-many relationship #7938

@jjklee121

Description

@jjklee121

Hi,

When running database first migration using Scaffold-DbContext the some of the models generated are linked by one-to-one relationships, when in actual fact they are one-to-many and I'm not getting any errors or exceptions.

Basically I have a table of jobs and a table of appointments.
A job can have multiple appointments and each of these appointments can have difference statuses e.g.
Active
Cancelled

image

So in my crude example above, Job1 has 3 appointments linked to it.

The thing that seems to be causing the issue I'm experiencing is an index I have on one of the tables which was recently added.

Previously without the index when Scaffold-DbContext was run the Job model looked something like this

        public Job()
        {
            Appointment = new HashSet<Appointment>();
            // more code
        }

        [InverseProperty("Job")]
        public virtual ICollection<Appointment> Appointment { get; set; }

But now with the index I am getting.

        public Job()
        {
            // more code
        }

        [InverseProperty("Job")]
        public virtual Appointment Appointment { get; set; }

When I remove the index it generates the models and the relationships correctly between Job and Appointment.

The index below is there to prevent multiple Active Appointments on a single Job at any given time.

CREATE UNIQUE NONCLUSTERED INDEX [IX_Appointment_JobId_NotActiveStatus_Unique] ON [Appointment] ([JobId] ASC) WHERE[StatusId] != 'Cancelled'

I'm not sure if there is anything to tell the scaffolding to ignore the index in this particular case?

Any help would be greatly appreciated.

Many thanks,

Jeremy

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No fields configured for Bug.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions