简体   繁体   中英

Mapping many-to-one relations in .Net core

Using .Net Core EF how do I map a many-to-one relation?

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. The example I saw was an Order and an OrderStatus .

The Order has a FK of the OrderStatus . But to map the relation in .Net they had the OrderStatus with a List<Order> and a [ForeignKey] annotation pointing to the Order.

This seems silly. What would I want an OrderStatus to know about ALL of the Orders that have that status???

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.

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???

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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