1

我們有一個模型,其中一個公共實體被其他實體(域)使用,我們希望以一種通用的方式在實體之間創建一個關係,如果可能。實體框架,當一個實體被其他幾個實體使用時建模場景

在這個例子中,該地址由學生和由學校和每個人都可以有一個或幾個地址,一個地址只能屬於一個實體(不多對多關係)

public class Address 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public int? RefId { get; set; } 
    } 

public class School 
    { 
     public int Id { get; set; } 
     public string SchoolName { get; set; } 
     public ICollection<Address> Address { get; set; } 
    } 

    public class Student 
    { 
     public int Id { get; set; } 
     public string StudentName { get; set; } 
     public ICollection<Address> Address { get; set; } 
    } 

EF6模型首先創建下面的模式(不帶任何附加的配置)

CreateTable(
       "dbo.Addresses", 
       c => new 
        { 
         Id = c.Int(nullable: false, identity: true), 
         Name = c.String(), 
         RefId = c.Int(), 
         School_Id = c.Int(), 
         Student_Id = c.Int(), 
        }) 
       .PrimaryKey(t => t.Id) 
       .ForeignKey("dbo.Schools", t => t.School_Id) 
       .ForeignKey("dbo.Students", t => t.Student_Id) 
       .Index(t => t.School_Id) 
       .Index(t => t.Student_Id); 

本質上,加入外鍵對於每個實體。這種模式很有效,但我們不確定這是否是最佳做法。

我們看到的問題是,當使用Address添加其他實體時,我們需要繼續添加與FK(例如Library - LibraryId)一起的新實體的ID。它打破了地址概念的抽象。

我們嘗試使用抽象參考ID(RefId)並配置EF將其用作FK鍵,但它爲同一個表創建了兩個FK。

另一種選擇是不使用任何導航屬性並手動填充和處理實體之間的關係 - 實際上不使用ORM功能。

由於這似乎是一個常見的情況,有沒有一種方法來以通用的方式建模?

+0

這裏的(反)模式名稱是* polymorpic associations *。使用這個作爲搜索詞,你會發現很多帖子讓你走上正確的軌道。 –

回答

0

的一種方法是創建一個抽象類和繼承:

public abstract class AddressRef 
{ 
    public int AddressId { get; set; } 

    // Navigational properties 
    public virtual Address { get; set; } 
} 

現在你可以繼承時,需要在地址引用上面的類:

public class School : AddressRef 
{ 
    // other properties 
} 

public class Student : AddressRef 
{ 
    // other properties 
} 

這將允許你只在一個地方管理參考,並根據需要在多個類中使用它。