0

I have 2 models:

public class TransactionHistory : IDbEntity {
    [Key]
    public int ID { get; set; }

    public ItemHistory ItemHistory { get; set; }
}

public class ItemHistory : IDbEntity {
    [Key]
    public int ID { get; set; }

    public int TransactionHistoryID { get; set; }
    public TransactionHistory TransactionHistory { get; set; }

}

There's a one to one relationship between TransactionHistory and ItemHistory, ItemHistory MUST have a TransactionHistory but TransactionHistory may or may not have an ItemHistory.

I want to be able to do this in code:

var test = db.ItemHistory.Include(x => x.TransactionHistory).ToList();

As well as:

var test2 = db.TransactionHistory.Include(x => x.ItemHistory).ToList();

But I only want a single FK on the ItemHistory table.

With the code I've listed I get this error:

Unable to determine the principal end of an association between the types 'InventoryLibrary.DomainModels.TransactionHistory' and 'InventoryLibrary.DomainModels.ItemHistory'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

How is this achieved in Entity Framework code first data annotations?

Smithy
  • 2,170
  • 6
  • 29
  • 61
  • possible duplicate of [Unable to determine the principle end of an association](http://stackoverflow.com/questions/20035021/unable-to-determine-the-principle-end-of-an-association) – Colin Jun 04 '14 at 13:53

1 Answers1

1

Firstly, you have to mark foreign keys by virtual keyword to enable overrides.

public class TransactionHistory : IDbEntity 
{
    [Key]
    public int ID { get; set; }
    public virtual ItemHistory ItemHistory { get; set; }
}

public class ItemHistory : IDbEntity 
{
    [Key]
    public int ID { get; set; }
    public int TransactionHistoryID { get; set; }
    [Required]    
    public virtual TransactionHistory TransactionHistory { get; set; }
}

If HistoryItem must have Transaction History, add DataAnnotation [Required], which makes it non-nullable.

Finally, wonder, if you want to have one-to-one relationship. I imagine you'd like to have many transaction history entries. Am I right? If not - let me know.

To create one-to-many relationship, use IEnumerable<> type.

magos
  • 3,371
  • 4
  • 29
  • 54
  • This was spot on, I do only want a one-to-one cardinality where the modality is 0 on the TransactionHistory end, because transaction history may not always have itemhistory associated with it :) – Smithy Jun 04 '14 at 15:29