0

I am trying to define the following model where Appointment table has foreign key for Person, and the entities both have navigation properties to each other.

public class Appointment
{
    public int AppointmentId { get; set; }

    // Foreign Key property (this will be created in DB)
    public int? PersonId { get; set; }

    // Navigation property to Flatmate
    public virtual Person Person { get; set; }
}

public class Person
{
    public int PersonId { get; set; }

    // Just navigation property. Don't want Person table to include foreign key (no need)
    public virtual Appointment Appointment { get; set; }
}

I try to use fluent config:

     modelBuilder.Entity<Appointment>()
            .HasOptional(a => a.Person)
            .WithOptionalDependent(p=> p.Appointment);

But I get an exception that its missing a column (either Appointment_AppointmentId or Person_PersonId, depending on whether I use WithOptionalDependent or WithOptionalPrincipal).

4

1 に答える 1

1

Entity Framework doesn't support this. HasOptional().WithOptionalDependent() can work when both tables use the same key (PersonId == AppointmentId), but that's not the situation you have. In order to ensure that one person doesn't have multiple appointments, you'd need to make sure PersonId is unique in the Appointment table, and Entity Framework doesn't support unique constraints.

What you could do (without changing your database) is map this as a one-to-many relation, where one person can have multiple appointments, and create a helper property to return the one appointment:

public virtual ICollection<Appointments> Appointments { get; set; }
[NotMapped]
public Appointment Appointment {
    get {
        return Appointments.SingleOrDefault();
    }
}

Note that Entity Framework won't understand the Appointment property, so you cannot use it in queries.

于 2012-10-05T11:45:25.803 に答える