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