MVC - 使用外键链接两个模型

时间:2016-02-08 15:51:41

标签: asp.net-mvc model-view-controller

如何在一对多关系中添加一个将我的Club类和我的ClubEvent类链接在一起的外键,其中Club是父类,而ClubEvent是孩子。

这些是我正在使用的模型

<input type="number" value="2">

input[type=number] {
  width: 9vw;
  height: 10vw;
  max-width: 42px;
  max-height: 52px;
  text-align: center;
  -moz-border-radius: 1px;
  -webkit-border-radius: 1px;
  border-radius: 1px;
  text-align: center;
  border: 3px solid black;
  display: inline-block;
  margin-left: 6%;
  background-color: black;
  color: white;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    /* display: none; <- Crashes Chrome on hover */
    -webkit-appearance: none;
    margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
    background: #eee url('http://i.stack.imgur.com/YYySO.png') no-repeat 50% 50%;  
    width: 14px;
    height: 14px;
    padding: 4px;
    position: relative;
    right: 4px;
    border-radius: 28px;
}

我想连接这两个表,以便我可以为俱乐部添加活动,这样我就可以只显示每个俱乐部的相关活动

1 个答案:

答案 0 :(得分:2)

这是非常基本的MVC,如果您将来需要这方面的帮助,请完成本教程:http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application这太棒了!

因为ClubEvent是一个孩子,所以&#39;俱乐部(意思是一个俱乐部可以有一个或多个事件)你想要引用孩子的父母。因此,您将添加对clubEvent的引用,将该对象的每个实例链接到相应的俱乐部。将其添加到您的ClubEvent对象..

public int ClubID {get; set;}

[ForeignKey("ClubID")]
public virtual Club Club {get;set;}

通过添加导航属性(虚拟俱乐部俱乐部),您将能够从ClubEvent儿童中调用父对象。 (俱乐部)this.ClubEvent。

通过使用父级俱乐部ID查询ClubEvents表,可以轻松实现此目的。像:

var events = db.ClubEvents.Where(e => e.ClubID == id)

在哪里&#39; id&#39;是传递给控制器​​中方法的ClubID。

希望这有帮助,如果您有任何问题,请检查此链接,因为它有很好的示例,适用于MVC中的每种关系类型。

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application