简体   繁体   English

EF代码首先对许多BaseEntity继承

[英]EF Code First Many to Many BaseEntity Inheritance

I would like all my entities that are inheriting BaseEntity to have collection of one entity, this is my Sample 我希望所有继承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; }
}

I would like to map it something like that, because by default table Notes has all ids of all tables (Student_Id, School_Id, etc) 我想将其映射为类似的内容,因为默认情况下,表Notes具有所有表的所有ID(Student_Id,School_Id等)

多对多

Any Ideas how to do this, or what to search? 任何想法如何做到这一点,或搜索什么?

You can add an ObjectId to the notes table, to point to the related object (student, school, etc). 您可以在注释表中添加一个ObjectId,以指向相关的对象(学生,学校等)。 And decorate your base class with the [ForeignKey("ObjectId")] attribute. 并使用[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();
    }
}

This is one to many relationship, and does not require a mapping table, as you are using Guids as primary keys, you do not need to worry about object ids repeating in different tables. 这是一对多的关系,并且不需要映射表,因为您使用Guid作为主键,因此您不必担心对象ID在不同表中重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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