Cezar
Cezar

Reputation: 355

Entity Framework several One-to-Many with same model

My Order class

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

        (...)

        [ForeignKey("Client")]
        public string ClientID { get; set; }
        public virtual ApplicationUser Client { get; set; }

        [ForeignKey("Trader")]
        public string TraderID { get; set; }
        public virtual ApplicationUser Trader { get; set; }

        [ForeignKey("Driver")]
        public string DriverID { get; set; }
        public virtual ApplicationUser Driver { get; set; }
    }

And my MS Identity ApplicationUser class:

public class ApplicationUser : IdentityUser
    {
        (...)
        public virtual List<Order> Orders { get; set; }
    }

As you can see I'd like to have speciffic users in speciffic "role" in Order model. How should I write a code in ApplicationUser to get speciffic lists of Clients, Traders and Drivers? I mean, I'd like to find user in database and then I'd like to have three lists named e.g. AsClient, AsTrader and AsDriver. Right now List<Orders> count is always 0.

Upvotes: 0

Views: 41

Answers (2)

Slava Utesinov
Slava Utesinov

Reputation: 13498

Use InversePropertyAttribute:

public class ApplicationUser : IdentityUser
{
    //another stuff...

    [InverseProperty("Client")]
    public virtual ICollection<Order> AsClient { get; set; }

    [InverseProperty("Trader")]
    public virtual ICollection<Order> AsTrader { get; set; }

    [InverseProperty("Driver")]
    public virtual ICollection<Order> AsDriver { get; set; }
}

Upvotes: 1

Endi Zhupani
Endi Zhupani

Reputation: 736

I would suggest you use a little inheritance here.

So you would create three classes that extend ApplicationUser, one for each Trader, Client and Driver. And then on each of these classes have the orders list. Also, on the Order class, change the types from ApplicationUser to the appropriate subtype.

Then as an inheritance strategy you can choose the table per hierarchy and follow the instructions on this link to implement it.

Hope this helps.

Upvotes: 0

Related Questions