How to define non mandatory record that has composite key

99 Views Asked by At

I have 3 models: Order, Organisation and OrderOrganisation.

Order will always exist, as will Organisation, but OrderOrganisation's existence is not mandatory.

One order can relate to many organisations, and this is the record that will header that information.

I can't change the database structure.

Here are my models.

public class Order
{
    public int Id { get; set; }

    public virtual ICollection<OrderOrganisation> OrderOrganisations { get; set; }
}

public class Organisation
{
    public int Id { get; set; }

    public virtual ICollection<OrderOrganisation> OrderOrganisations { get; set; }
}

public class OrderOrganisation
{
    [Key, Column(Order = 0)]
    public int OrderId { get; set; }

    [Key, Column(Order = 1)]
    public int OrganisationId { get; set; }

    [ForeignKey("OrderId")] //this is not right, i get an inner join not an outer join
    public virtual Order Order { get; set; }

    [ForeignKey("OrganisationId")] //this is not right, i get an inner join not an outer join
    public virtual Organisation Organisation { get; set; }
}

I know I need to add something to the context but I can't work out what?

Thanks

1

There are 1 best solutions below

1
On
//try this
public class Order
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<OrderOrganisation> OrderOrganisations { get; set; }
}

public class Organisation
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<OrderOrganisation> OrderOrganisations { get; set; }
}

public class OrderOrganisation
{
    [ForeignKey("Order"), Column(Order = 0)]
    public int? OrderId { get; set; }

    [ForeignKey("Organisation"), Column(Order = 1)]
    public int? OrganisationId { get; set; }

    [ForeignKey("OrderId")]
    public virtual Order Order { get; set; }
    [ForeignKey("OrganisationId")]
    public virtual Organisation Organisation { get; set; }
}