如何与每晚最新发布的EF Core建立多对多关系? [英] How to create a many to many relationship with latest nightly builds of EF Core?

查看:84
本文介绍了如何与每晚最新发布的EF Core建立多对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Fluent API在 EF7 EF Core中的两个表之间创建多对多关系?例如,假设您有以下表格:

How do you use the Fluent API to create a many to many relationship between two tables in EF7 EF Core? For example, say you have the following tables:

如何利用DbContext类中的modelBuilder定义这样的关系?

How would one leverage the modelBuilder in the DbContext class to define a relationship like this?

我看过 this 链接与此主题有关,但这是去年发出的,我想知道 EF7 EF Core中是否有有关如何解决此问题的新信息。

I've seen this link from the EF team's meeting notes regarding this subject, but it is from last year and am wondering if there is new information on how to approach this in EF7 EF Core.

我能够在Photos和PhotosPeople之间以及People和PhotosPeople之间建立一对多关系。数据库是按我的意愿生成的,但是人与照片之间的导航现在需要与中间实体进行交互。我想避免这种情况。

I am able to create one to many relationships between Photos and PhotosPeople as well as People and PhotosPeople. The database is generated as I'd like it to be, but the navigation between People and Photos now requires interaction with an intermediate entity. I'd like to avoid this.

推荐答案

#1368 。解决方法是将联接表映射到实体:

This is tracked by #1368. The workaround is to map the join table to an entity:

class Photo
{
    public int Id { get; set; }
    public ICollection<PersonPhoto> PersonPhotos{ get; set; }
}

class PersonPhoto
{
    public int PhotoId { get; set; }
    public Photo Photo { get; set; }

    public int PersonId { get; set; }
    public Person Person { get; set; }
}

class Person
{
    public int Id { get; set; }
    public ICollection<PersonPhoto> PersonPhotos{ get; set; }
}

请务必配置 PersonPhoto 和组合键:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<PersonPhoto>().HasKey(x => new { x.PhotoId, x.PersonId });
}

要导航,请使用Select:

To navigate, use a Select:

// person.Photos
var photos = person.PersonPhotos.Select(c => c.Photo);

这篇关于如何与每晚最新发布的EF Core建立多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆