EF Core - Mapping Many-to-One

entity-framework entity-framework-core

Question

I'm trying to create a mapping between the 2 tables using EF Core Data Annotation.

So here's my sample scenario. Let's suppose I have theses classes that consist of following properties

Orders

[Key] 
public int OrderId {get;set}
public string OrderNumber {get;set;}

OrderStatuses

[Key]
public int OrderStatusId {get;set}
public string OrderNumber {get;set;}
public StatusEnum Status {get;set} // Pending, Delivered, Cancel

I have this example data:

OrderId                 OrderNumber // Order Table
1                       11111
2                       11111
3                       11111
4                       22222

OrderStatusId           OrderNumber         Status
1                       11111               Pending
2                       22222               Pending

Basically, I created OrderStatuses table that stores the status of the OrderNumber but they have no relationship since I have no idea how to make them Many-to-One using Data Annotation of Entity Framework Core without using the key. I want to achieve this so I can use the .Include method in fetching all the info.

The key is, Many Orders but One Status only. I hope somebody helps me.

1
1
2/12/2019 6:00:48 AM

Accepted Answer

As you are wanting many-to-one between Order and OrderStatus, It seems you have configured your model relation wrongly.

So your OrderStatus and Order model class should be as follows:

public class OrderStatus
{
    [Key]
    public int OrderStatusId { get; set; }
    public StatusEnum Status { get; set; }

    public ICollecton<Order> Orders {get; set;}
}

public class Order
{
    [Key]
    public int OrderId { get; set; }

    public string OrderNumber { get; set; }

    public OrderStautsId {get;; set;}

    public OrderStatus OrderStatus { get; set; }
}
1
2/12/2019 5:43:07 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow