在我的应用程序中,一笔交易最多可以有四个与之关联的项目。当我意识到当我调用 transactionId
来显示某个交易的详细信息时,我遇到了问题,我应该如何拉取与其关联的项目?我做了一些研究,发现多对多似乎是可行的方法。我以前从未与多对多合作过。如何设置这样的东西?教程、指南任何东西都会有很大帮助,因为我被困住了。
商品型号
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; }
}
交易模型
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
}
最佳答案
您需要做的就是向您的事务模型添加一个导航属性,如下所示:
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; }
}
现在将导航属性添加到您的项目模型中:
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; }
}
现在您需要告诉 Entity Framework 您有一个多对多关系。为此,我们可以在 DbContext
中使用 OnModelCreating()
重写,如下所示:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Transaction>().HasMany(e=>e.items).WithMany(e=>e.transactions);
}
现在这两个表已链接在一起。希望这有帮助:)
关于database - 为多对多关系 Entity Framework MVC 4 设置数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18439272/