当连接表有额外字段时,利用实体框架的多对多关系

发布于 2024-10-05 12:23:27 字数 461 浏览 1 评论 0原文

一个场景:

在我的数据库中,我有一个将“客户”和“电影”连接在一起的表,并有一个额外的字段指定关系的权重。 EG:

CustomersMovies
  | -CustomerID
  | -MovieID
  | -Weight 

如果我只有前两个字段,实体框架将识别多对多关系,我将能够调用 Customer.Movies 和 Movie.Customers。到了第三个字段,这种关系就被打破了。

理想情况下,我希望能够使用 Customer.Movies[0].Weight 或类似的方法来返回连接参数。即使不支持这一点,我仍然希望其他功能的多对多关系。

实体框架中是否支持类似的内容?我几乎要创建两个表,CustomersMovies(仅连接两个表)和 CustomerMovieWeights 表,该表指定给定客户和电影的权重,但冗余数据并不理想。

亲切的问候, 哈利

A scenario:

In my database I have a table joining Customers and Movies together, with an extra field specifying the weight of the relation. EG:

CustomersMovies
  | -CustomerID
  | -MovieID
  | -Weight 

If I only had the first two fields, the Entity Framework would recognise the many-to-many relationship and I would be able to call Customer.Movies and Movie.Customers. With the third field, this relationship is broken.

Ideally, I would love to be able to go Customer.Movies[0].Weight or something similar to return the joining parameter. Even if this is not supported, I would still like the many-to-many relationship for other functions.

Is anything like this supported within the Entity Framework? I am almost about to create two tables, CustomersMovies (which just joins the two tables) and a CustomerMovieWeights table which specifies the weight for a given customer and movie, but the redundant data isn't ideal.

Kind Regards,
Harry

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

葮薆情 2024-10-12 12:23:28

如果您从联结表中删除了权重列,则只需映射客户电影表。

如果没有,您将需要映射所有三个表:CustomerCustomerMoviesMovies

但是,当然,您将无法执行此操作:

var customer = ctx.Customers.First();
var customerMovies = customer.Movies;

您必须执行此操作:

var customer = ctx.Customers.First();
var customerMovies = customer.CustomerMovies.Movies;

因为客户将没有到电影的直接导航属性 - 它将有一个将导航属性设置为 CustomerMovie(反之亦然)。

老实说,我会同意你最后的想法。让 CustomerMovies 表仅包含 FK(CustomerId、MovieId),以及另一个用于权重的“类似元数据”表。

这样您就可以在 EDMX 中正确映射多对多。

If you dropped the Weight column from the junction table, then you would only need to map Customers and Movies table.

If not, you will need to map all three tables: Customer, CustomerMovies and Movies.

But of course, you will not be able to do this:

var customer = ctx.Customers.First();
var customerMovies = customer.Movies;

You will have to do this:

var customer = ctx.Customers.First();
var customerMovies = customer.CustomerMovies.Movies;

Because Customer will not have a direct navigational property to Movie - it will have a navigational property to CustomerMovie (and vice versa).

Honestly though, i would go with your last idea. Have the CustomerMovies table contain only the FK's (CustomerId, MovieId), and another "meta-data-like" table for weights.

This way you can map your many-to-many properly in the EDMX.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文