c# - 多个多对多关系 Entity Framework

标签 c# entity-framework ef-code-first ef-fluent-api

主要目标是能够在 Mucle 表和 Exercise 表之间建立多对多关系。我想要一个既有主要肌肉群又有次要肌肉群的练习。

是否可以在一个模型中有两个 icollection 而在另一个模型中只有一个? 如果有人也可以帮助“流畅的配置”,我将不胜感激!

这是我现在得到的代码。

public class Muscle
    {
        public int MuscleID { get; set; }
        public bool IsFront { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Exercise> Exercises { get; set; }
    }

    public class Exercise
    {
        public int ExerciseID { get; set; }
        // ExerciseCategory
        public int ExerciseCategoryID { get; set; }
        public DateTime CreationDate { get; set; }
        public string Description { get; set; }
        public string Name { get; set; }

        public virtual ExerciseCategory ExerciseCategory { get; set; }
        public virtual ICollection<Muscle> Muscles { get; set; }
        public virtual ICollection<Muscle> MusclesSecondary { get; set; }
    }

最佳答案

无法映射您描述的模型。
要映射您的模型(2 n-m 关系),您需要一个带有鉴别器的连接表,而您不能使用 EF 来实现。

您可以通过多种方式更改模型以使其与 EF 一起使用

  • 您为 Junction 表创建一个模型(一个类)并在其中插入一个鉴别器。你的模型改变了(我认为新模型不太清楚)
  • 为什么有 Muscles 和 MusclesSecondary?能不能用Muscle这个属性来区分?在这种情况下,您可以在 Muscle 中拥有该属性并删除 Exercise.MusclesSecondary 然后您只有 EF 使用 Junction 表处理的 n-m 关系。
  • 如果您想要此模型,您可以向 Muscle 添加 2 个集合(例如 ExcercisesMuscle 和 ExercisesMusclesSecondary)和第三个未映射的集合,其中包含 ExcercisesMuscle 和 ExercisesMusclesSecondary 的内容。关于 ExcercisesMuscle 和 ExercisesMusclesSecondary 它们可以是可观察的集合,因此您可以有效地缓存 Exercises 集合的内容。

关于c# - 多个多对多关系 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39587982/

相关文章:

c# - 如何用HttpWebRequest模拟浏览器文件上传

c# - 在 Entity Framework 中获取被忽略的属性

entity-framework - 我不能在事务范围内的Entity Framework中调用存储过程吗?

entity-framework - EF Code First 错误地重命名表,这是一个错误吗?

asp.net-mvc-3 - ASP.NET MVC 3 一对多无法更新桥接表

c# - 比 decimal.Parse 更快的替代方法

javascript - json stringify 不能在 asp.net mvc 页面上工作

c# - 即使宣布公开也无法访问属性(property)

c# - 为什么 IQueryable 上的 .Where() 根据是否将 Lamba 或 Func<T,Tresult> 作为参数传递返回不同的类型

entity-framework - 急切加载包括派生类的导航属性