0

我有以下 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 将创建包含两列的表Attachments : ProjectIdExperimentId

我如何告诉 EF 我的关系 Experiment->Attachment 和 Project->Attachment 必须在 Attachment 上“共享”相同的键?

就像是:

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 中尝试过,但没有找到解决方案。

谢谢,圭多

4

1 回答 1

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);
于 2013-07-22T17:58:33.643 回答