简体   繁体   中英

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

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)

多对多

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). And decorate your base class with the [ForeignKey("ObjectId")] attribute.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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