简体   繁体   English

在 .Net 核心中映射多对一关系

[英]Mapping many-to-one relations in .Net core

Using .Net Core EF how do I map a many-to-one relation?使用 .Net Core EF 如何映射多对一关系?

I am trying to map a many-to-one relation.我正在尝试映射多对一关系。 All of the samples I see assume that you map a one-to-one relation (ie Attendee has the FK of the ticket and the ticket has the FK of the Attendee) or they assume that the subordinate object will hold a collection of the main object.我看到的所有示例都假设您映射一对一关系(即参加者具有票的 FK,票具有参加者的 FK),或者他们假定从属对象将持有主要对象的集合目的。 The example I saw was an Order and an OrderStatus .我看到的例子是OrderOrderStatus

The Order has a FK of the OrderStatus . Order具有OrderStatus的 FK。 But to map the relation in .Net they had the OrderStatus with a List<Order> and a [ForeignKey] annotation pointing to the Order.但是为了在 .Net 中映射关系,他们有OrderStatus和一个List<Order>和一个 [ForeignKey] 注释指向订单。

This seems silly.这似乎很愚蠢。 What would I want an OrderStatus to know about ALL of the Orders that have that status???我希望OrderStatus了解所有具有该状态的Orders

Example:例子:

class Order {
    long orderId;
    OrderStatus status;
    ...
}

class OrderStatus {
   long orderStatusId;
   String code;
   String description;
   int severityLevel;
   ...
}

In the Database the Order table would have a FK column holding the orderStatusId.在数据库中,Order 表将有一个 FK 列保存 orderStatusId。

How does one do a simple many-to-one mapping for this?如何为此做一个简单的多对一映射?

What would I want an OrderStatus to know about ALL of the Orders that have that status???我希望 OrderStatus 了解所有具有该状态的订单?

Yes!是的! possible!.可能的!。 write your model classes as follows:编写您的模型类如下:

public class OrderStatus 
{
   [Key]
   public long orderStatusId { get; set; }
   public string string code { get; set; }
   public string description { get; set; }
   public int severityLevel { get; set; }
   ...........

}

public class Order 
{
    [Key]
    public long orderId { get; set; }

    [ForeignKey("OrderStatus")]
    public long orderStatusId { get; set; }
    ..........

    public OrderStatus OrderStatus { get; set; }
}

Then in the query:然后在查询中:

var orders =  _dbContext.Orders.Where(o => o.orderStatusId == 1).ToList(); // <-- Here is all the Orders with statusId '1'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM