考慮3類:Person
,Company
和File
。EF代碼優先:具有多個多對一關係的實體類型
Person
和Company
是完全不同且無關的,但它們每個都有一個File
對象的集合。無論它屬於哪個實體,File
總是具有相同的結構。
這個問題是關於如何最好地模擬File
可以具有的多對多關係;在這種情況下,File
可以與Person
或Company
(但不在同一實例中)具有多對一的關係。
方法1:
class Person
{
public int Id {get;set;}
public ICollection<File> Files {get;set;}
}
class Company
{
public int Id {get;set;}
public ICollection<File> Files {get;set;}
}
class File
{
public int Id {get;set;}
public string Path {get;set;}
}
/*
EF Generates:
-----------------
Table: Person (Id)
Table: Company (Id)
Table: File (Id, Path, Person_Id, Company_Id)
*/
這似乎是最簡單的,並從代碼最簡單的第一視角,這是我最喜歡的。問題是表File
,它具有Person_Id和Company_Id的無效字段。從數據庫設計的角度來看,這看起來是錯誤的,考慮到兩個字段中只有一個字段會有值,而另一個永遠是空的。使用文件集合添加更多類會更加激化問題。
方法2:
class Person
{
public int Id {get;set;}
public ICollection<PersonFile> Files {get;set;}
}
class Company
{
public int Id {get;set;}
public ICollection<CompanyFile> Files {get;set;}
}
class File
{
public int Id {get;set;}
public string Path {get;set;}
}
class PersonFile
{
public Person Person {get;set;}
public File File {get;set;}
}
class CompanyFile
{
public Company Company {get;set;}
public File File {get;set;}
}
/*
EF Generates:
------------------
Table: Person (Id)
Table: Company (Id)
Table: File (Id, Path)
Table: PersonFile (Person_Id, File_Id)
Table: CompanyFile (Company_Id, File_Id)
*/
這樣可以完成同樣的事情方法1,並且是接近我已經在第一DB傳統設計完成。但它需要兩個額外的類,我真的不需要......或者我呢?我想這是這個問題的點...
當設計守則第一實體框架應用程序,做我需要擔心的數據庫模式?在方法1中,我可以優先考慮數據庫設計的代碼/模型簡化嗎?還是應該像方法2一樣,在腦海中編寫數據庫設計類?
謝謝!響應和鏈接都非常有幫助! –