[英]EF Code First Many to Many BaseEntity Inheritance
我希望所有繼承BaseEntity的實體都具有一個實體的集合,這是我的示例
public abstract class BaseEntity : IEntity
{
[Key]
public Guid Id { get; set; }
public virtual ICollection<Note> Notes { get; set; }
protected BaseEntity()
{
Id = Guid.NewGuid();
Notes = new List<Note>();
}
}
public class Note
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public Note()
{
Id = Guid.NewGuid();
}
}
public class Student : BaseEntity
{
public string Name { get; set; }
public School School { get; set; }
public string SomeInfo { get; set; }
}
public class School : BaseEntity
{
public string Name { get; set; }
public int Rating { get; set; }
public int Size { get; set; }
}
我想將其映射為類似的內容,因為默認情況下,表Notes具有所有表的所有ID(Student_Id,School_Id等)
任何想法如何做到這一點,或搜索什么?
您可以在注釋表中添加一個ObjectId,以指向相關的對象(學生,學校等)。 並使用[ForeignKey(“ ObjectId”)]屬性裝飾您的基類。
public abstract class BaseEntity : IEntity
{
[Key]
public Guid Id { get; set; }
[ForeignKey("ObjectId")]
public virtual ICollection<Note> Notes { get; set; }
protected BaseEntity()
{
Id = Guid.NewGuid();
Notes = new List<Note>();
}
}
public class Note
{
[Key]
public Guid Id { get; set; }
public Guid ObjectId { get; set; } //student, school, etc
public string Name { get; set; }
public string Value { get; set; }
public Note()
{
Id = Guid.NewGuid();
}
}
這是一對多的關系,並且不需要映射表,因為您使用Guid作為主鍵,因此您不必擔心對象ID在不同表中重復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.