EF代码首先多对多BaseEntity继承

时间:2015-03-03 16:00:26

标签: c# .net entity-framework

我希望我继承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等)

ManyToMany

任何想法如何做到这一点,或搜索什么?

1 个答案:

答案 0 :(得分:2)

您可以将ObjectId添加到notes表中,以指向相关对象(学生,学校等)。并使用[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();
    }
}

这是一对多关系,并且不需要映射表,因为您使用Guids作为主键,您不必担心在不同表中重复的对象ID。