EF4 - 指向多个表的外键

时间:2013-07-22 09:54:37

标签: entity-framework foreign-keys foreign-key-relationship

我有以下3个表格:

public class Project
{
    // other fields...

    public virtual ICollection<Attachment> Attachments { get; set; }
}

public class Experiment
{
    // other fields...

    public virtual ICollection<Attachment> Attachments { get; set; }
}

public class Attachment
{
    // ...
}

如果我创建此结构,EF将使用两列创建表附件 ProjectId ExperimentId

我如何告诉EF我的关系实验 - &gt;附件和项目 - &gt;附件必须在附件上“共享”相同的密钥?

类似的东西:

public class Attachment
{
    // other fields...

    // can be a Guid from either Experiment or Project
    public Guid BelongingModelId { get; set; }

    // I will set this manually in order to know from which table the Guid is coming
    public String BelongingModelType { get; set; }
}

可以这样做吗?

我在DbContext / OnModelCreating中尝试过,但我找不到任何解决方案。

谢谢, 吉

1 个答案:

答案 0 :(得分:0)

一种方法是使Project和Experiment继承自基类。

public class Model
{
    // other common fields...

    public virtual ICollection<Attachment> Attachments { get; set; }
}

public class Project : Model
{
    // project fields...     
}

public class Experiment : Model
{
    // experiment fields...
}

public class Attachment
{
    // other fields...

    public virtual Model Model { get; set; }
}

你必须做一些演员才能找出给定附件的模型。

var project = attachment.Model as Project;
if (project != null)
{
    // you have a project
}
var experiment = attachment.Model as Experiment;
if (project != null)
{
    // you have an experiment
}

或者您可以告诉EF只为您提供特定类型模型的附件。

var attachments = context.Attachments.Where(a => a.Model is Project);