0

我有以下3个表:EF4 - 外键指向多个表

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将创建表附件有两列:专案编号ExperimentId

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

喜欢的东西:

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

感谢, 圭多

回答

0

一种方法是使项目和实验从基类继承。

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