Reputation: 1815
in my application a transaction can have up to four items associated with it. I ran into the problem when I realized when I call to a transactionId
to display the specifics of a certain transaction how was I supposed to pull down the items associated with it? I did some research and found that many to many seems the way to go. I've never worked with many to many before. How to set something like this up? Tutorials, guides anything would be a big help because I'm stuck.
Item model
public class Item
{
public int user_id { get; set; }
public int ID { get; set; }
public string item_name { get; set; }
public string item_description { get; set; }
public string item_code { get; set; }
public DateTime dateAdded { get; set; }
public int catId { get; set; }
public int? isSelected { get; set; }
public int isQuick { get; set; }
}
public class ItemDBContext : DbContext
{
public ItemDBContext()
: base("name=ItemDbContext")
{ }
public DbSet <Item> Items { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Transaction> Transactions { get; set; }
}
Transaction model
public class Transaction
{
[Key]
public int transactionID { get; set; }
public int FromUserID{ get; set; }//user logged in
public int toUserId { get; set; } //user to be sent
public int itemForId { get; set; } //single item
public int itemsSent { get; set; }//multiple values
}
Upvotes: 2
Views: 669
Reputation: 2609
All you need to do is add a navigation property to your Transaction Model like this:
public class Transaction
{
[Key]
public int transactionID { get; set; }
public int FromUserID{ get; set; }//user logged in
public int toUserId { get; set; } //user to be sent
public int itemForId { get; set; } //single item
public int itemsSent { get; set; }//multiple values
//Navigation Property
public ICollection<Item> items { get; set; }
}
Now add the navigation property to your Item Model:
public class Item
{
public int user_id { get; set; }
public int ID { get; set; }
public string item_name { get; set; }
public string item_description { get; set; }
public string item_code { get; set; }
public DateTime dateAdded { get; set; }
public int catId { get; set; }
public int? isSelected { get; set; }
public int isQuick { get; set; }
//Navigation Property
public ICollection<Transaction> transactions { get; set; }
}
now you need to tell Entity framework that you have a many-to-many relationship. For this we can use the OnModelCreating()
override inside your DbContext
like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Transaction>().HasMany(e=>e.items).WithMany(e=>e.transactions);
}
now you these two tables are linked together. Hope this helps :)
Upvotes: 2