Reputation: 509
I currently have the following database structure:
TableA
(itemCode int, itemCategoryCode int, itemDescription description
) TableB
(id int, itemCode int, itemCategoryCode int
) TableA's PK is (itemCode, itemCategoryCode)
. TableB's PK is id
and FK is (itemCode, itemCategoryCode)
.
I need to set up EF such that i have a one to many relationship between TableA and TableB. And such that when I grab the object from TableB the navigational property of TableA is populated.
How do I set up my POCO classes with annotations to achieve this and/or fluent API?
Thanks.
Upvotes: 0
Views: 46
Reputation: 16149
With Data Annotations:
Table A:
public class TableA {
[Key, Column(Order=0)]
public int itemCode { get; set; }
[Key, Column(Order=1)]
public int itemCategoryCode { get; set; }
public virtual ICollection<TableB> TableBs { get; set; }
}
TableB:
public class TableB {
[Key]
public int ID { get; set; }
[ForeignKey("TableARecord"), Column(Order=1)]
public int itemCode { get; set; }
[ForeignKey("TableARecord"), Column(Order=2)]
public int itemCategoryCode { get; set; }
public virtual TableA TableARecord { get; set; }
}
Upvotes: 1
Reputation: 1942
just add a Virtual Collection property to the "Many" class, and a property of type "One" to your "Many" class see below code from http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
public class Student
{
public Student() { }
public int StudentId { get; set; }
public string StudentName { get; set; }
public virtual Standard Standard { get; set; }
}
public class Standard
{
public Standard()
{
StudentsList = new List<Student>();
}
public int StandardId { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
Upvotes: 0