且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何与最新的 EF Core 每晚构建建立多对多关系?

更新时间:2023-02-15 17:54:32

此内容由 #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);