且构网

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

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

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

#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);