繁体   English   中英

EF代码首先对许多BaseEntity继承

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM