如何定义具有组合键的非强制记录

时间:2014-11-20 13:22:48

标签: c# entity-framework foreign-keys composite-primary-key

我有3个模型:Order,Organization和OrderOrganisation。

订单将始终存在,组织也将如此,但OrderOrganisation的存在不是强制性的。

一个订单可以与许多组织相关,这是将该信息标题化的记录。

我无法更改数据库结构。

以下是我的模特。

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; }
}

我知道我需要在上下文中添加一些内容,但我无法解决问题?

由于

1 个答案:

答案 0 :(得分:0)

//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; }
}