Theo
Theo

Reputation: 473

EF Code First add a 0 to 1 relation to Model and Entities

I'm trying to define the model

 public class Refund
{
    [Key]   
    public int RefundID { get; set; }

    public int Order { get; set; }
    public int? TicketID { get; set; }
    public decimal? RefundTotal { get; set; }   
    public string RefundType { get; set; }
    public DateTime? RefundDate { get; set; }

    [ForeignKey("TicketID")]
    public virtual Ticket Ticket { get; set; }

}

My problem is that I would like to have access to the refund from the Ticket object, but the FK is on the refund Table. Something like this :

Public class Ticket
{
    [Key]
    public int TicketID { get; set; }


    public virtual Refund Refund { get; set; }

}

I tried to define it with the .HasOptional() command from EF but can't make it work.

I don't really know if that is possible, any ideas?

Upvotes: 0

Views: 38

Answers (2)

Theo
Theo

Reputation: 473

I actually found the solution :

Public class Ticket
{
    [Key]
    public int TicketID { get; set; }


    public virtual ICollection<Refund> Refund { get; set; }

}

As It is actually 0 to many relationship.

Sorry about that.

Upvotes: 1

Joe
Joe

Reputation: 37

Something to this effect would work:

Refund foundRefund = Refunds.SingleOrDefault(r => r.Ticket.Id == passedInTicketId);

Upvotes: 1

Related Questions