2

Are there any ways to configure conditional navigations in EF6 code-first (or EDMX, for that matter).

I have an entity type that will be referenced my multiple other types.

An attachment belongs to either a Person or a Vehicle. A person or a vehicle could have many attachments. There will likely be more types that have many attachments.

I know I could create a nullable Foreign Key on Attachments for each type, or create a 1 - 0..1 - * table for each type, but I would like to keep it all in the one table and not have to add more columns if possible.

public class Attachment {
    public virtual Person Person {get;set;}
    public virtual Vehicle Vehicle {get;set;}

    // how I want to achieve it (i.e. columns I would expect to see in the DB):
    public Type ForeignType {get;set;} // typeof(Person), typeof(Vehicle), etc
    public int ForeignKey {get;set;}
}
public class Person { 
    public int Id {get;set;}
    public virtual ICollection<Attachment> Attachments {get;set;}
}
public class Vehicle {
    public int Id {get;set;}
    public virtual ICollection<Attachment> Attachments {get;set;}
}

I would then like to configure the relationship something like...

modelBuilder.Entity<Attachment>()
    .HasOptional<Person>(a => a.Person).When(a => a.ForeignType == typeof(Person))
    .WithMany(p => p.Attachments);

modelBuilder.Entity<Attachment>()
    .HasOptional<Vehicle>(a => a.Vehicle).When(a => a.ForeignType == typeof(Vehicle))
    .WithMany(p => p.Attachments);

Is something similar to this possible, or should I just implement one of the other solutions?

AndrewP
  • 1,598
  • 13
  • 24
  • If you want to ensure that each `Attachment` is mandatory related to a `Person` xor `Vehicle`, the only way I can think of is having a common base class for `Person` and `Vehicle`, then configure a relation between `Attachment` and this base class. – grek40 Jan 12 '17 at 07:51

0 Answers0