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

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

问题描述

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

如何利用 DbContext 类中的模型构建器来定义这样的关系?

我见过 this 来自 EF 团队会议记录中关于此主题的链接,但它是去年的,我想知道是否有关于如何在 EF7 EF Core 中解决此问题的新信息.>

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

解决方案

此内容由 #1368 跟踪.解决方法是将连接表映射到实体:

class Photo{公共 int Id { 获取;放;}公共 ICollectionPersonPhotos{ 获取;放;}}类 PersonPhoto{公共 int PhotoId { 获取;放;}公开照片照片{得到;放;}公共 int PersonId { 获取;放;}公共人人{得到;放;}}班级人物{公共 int Id { 获取;放;}公共 ICollectionPersonPhotos{ 获取;放;}}

务必使用复合键配置PersonPhoto:

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

要导航,请使用选择:

//person.Photosvar 照片 = person.PersonPhotos.Select(c => c.Photo);

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:

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

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.

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.

解决方案

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; }
}

Be sure to configure PersonPhoto with a composite key:

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

To navigate, use a Select:

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

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

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