本文介绍了地图多对多关系没有导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以映射多对多关系而不在其中一个端点上导航属性?例如,我有一些小部件和一些用户可以对特定的小部件进行加载。我希望能够看到用户关心的小部件是什么,但是我不太在乎看到所有的用户已经加入了特定的小部件。

Is is possible to map a many to many relationship without having a navigation property on one of the ends? For example I have some widgets and some users who can star particular widgets. I'd like to be able to see what widgets a user cares stars, but I don't really care about seeing all the users who have starred a particular widget

Widget .cs

Widget.cs

public int Id { get; set; }
public string Name { get; set; }

User.cs

public int Id { get; set; }
public string Username { get; set; }
public ICollection<Widget> StarredWidgets { get; set; }

使用此设置,EF将从Widget向用户生成一对多关系。但是,它需要很多到许多。我意识到我可以添加一个 public ICollection< User>用户 Widget.cs ,但只要看看是否有其他方法。

With this setup, EF will generate a one-to-many relationship from Widgets to Users. However, it needs to be a many to many. I realize I could add a public ICollection<User> Users to Widget.cs, but just seeing if there was another way around this.

推荐答案

您可以和这种情况必须定义与Fluent API的多对多关系:

You can and this case must define the many-to-many relationship with Fluent API:

modelBuilder.Entity<User>()
    .HasMany(u => u.StarredWidgets)
    .WithMany() // <- no parameter here because there is no navigation property
    .Map(m =>
    {
        m.MapLeftKey("UserId");
        m.MapRightKey("WidgetId");
        m.ToTable("UserWidgets");
    });

这篇关于地图多对多关系没有导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 09:14