【问题标题】:How to have Many to Many Association in Entity Framework Code First如何在实体框架代码中首先进行多对多关联
【发布时间】:2011-05-14 04:49:17
【问题描述】:

我刚刚开始使用 EF,并且观看了一些很棒的教程视频。我被以下问题困住了。

我有一个文件集合类,我希望这些文件与事件和/或人相关联

public class file{
    public int id {get;set;}
    public string path {get;set;}
}

public event {
    public int id {get;set;}
    public string eventname {get;set}
    public virtual ICollection<file> files {get;set;}
    public event(){ files = new list<file>();}
}

public person {
    public int id {get;set;}
    public string name {get;set}
    public virtual ICollection<file> files {get;set;}
    public person(){ files = new list<file>();}
}

现在当我生成数据库时,我的文件表有一个 PersonID 和 EventID。

我希望能够让用户将文件附加到人员和/或事件。

【问题讨论】:

  • 现在数据库和对象模型都设置好了,任何关于我应该如何接近控制器和视图以添加新人员并允许用户上传文件并在文件之间建立必要关系的建议和人?

标签: c# entity-framework entity-framework-4 ef-code-first


【解决方案1】:

您得到的是 EF Code First 在将 1 到多关联映射到数据库方面的默认行为。 例如,您在 Person 类上有一个 ICollection&lt;File&gt;,因此,EF 将在 Files 表 (PersonId) 上创建一个 FK 并将其映射到 Persons 表上的 Id PK。

现在,我的猜测是,您喜欢在 File 和 Person 之间建立 多对多 关系,这样每个文件可以与多个 Person 相关,每个 Person 可以有多个文件(Event 对象的故事与好吧)。实现此目的的一种方法是将导航属性放在指向 Event 和 Person 类的 File 类上。所以,你的模型应该改成这样:

public class File {
    public int Id { get; set; }
    public string Path { get; set; }
    public virtual ICollection<Event> Events { get; set; }
    public virtual ICollection<Person> Persons { get; set; }
}

public class Event {
    public int Id { get; set; }
    public string EventName { get; set; }
    public virtual ICollection<File> Files {get;set;}
}

public class Person {
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<File> Files { get; set; }
}

public class MyContext : DbContext {
    public DbSet<Person> Persons { get; set; }
    public DbSet<Event> Events { get; set; }
    public DbSet<File> Files { get; set; }
}

因此,EF 将创建链接表(Events_Files 和 Files_Persons)以将这些多对多关联映射到数据库。

更新:
将 POCO 与 EF 一起使用时,如果您将导航属性标记为 虚拟,您将选择加入一些额外的 EF 支持,例如 延迟加载关系修复。所以一般来说,在导航属性中使用虚拟关键字被认为是一种很好的做法。

【讨论】:

  • 我很确定链接表(文件类)应该是“公共虚拟事件”而不是 ICollection。顺便说一句,我知道导航属性,但不知道虚拟关键字。好提示。谢谢。
  • 当使用上面的例子时,创建一个新的关系也会在相关表中添加一个新的项目。因此,在这种情况下,您拥有 File 并执行以下操作: File.Events = new Eventlist(其中 eventlist 填充了从数据库中检索到的事件) db.savechanges 不仅在 Events_Files 中添加了关系记录,还在 Events 表中添加了一个事件。在 events_files 中添加关系记录而不是在 events 中添加额外记录的正确方法应该是什么。
  • @Mounhim 您应该将其作为一个单独的问题提出。但与此同时,我想你可以试试MyContext.Events.Attach(...)
猜你喜欢
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多