定义条件关系

时间:2017-01-12 03:18:59

标签: c# entity-framework-6 ef-database-first ef-code-first-mapping

是否有任何方法可以在EF6代码优先(或EDMX)中配置条件导航。

我有一个实体类型,将引用我的多个其他类型。

附件属于人员或车辆。一个人或一辆车可能有很多附件。可能会有更多具有许多附件的类型。

我知道我可以为每种类型的附件创建一个可以为空的外键,或者为每种类型创建一个1 - 0..1 - *表,但我想将它全部保存在一个表中而不是必须如果可能的话,添加更多列。

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;}
}

我希望将这种关系配置为......

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);

是否有类似的可能,或者我应该只实施其他解决方案之一?

0 个答案:

没有答案