【问题标题】:Design models with two 'one-to-many' relationships in asp.net mvc3在 asp.net mvc3 中设计具有两个“一对多”关系的模型
【发布时间】:2013-05-30 19:45:33
【问题描述】:

我在使用实体框架在 ASP.NET MVC 3 中设计我的数据库时遇到问题。我遵循了一些教程并尝试适应我的需要。第一次使用ASP...

我有三个表:Person、Category 和 Example。

一个示例将在属于某个人的类别中,反之亦然:一个人可能有多个类别,每个类别可能有多个示例。

我想我应该用两个“一对多”的关系来设计它。那是我的模型:

public class Person 
{
  public int PersonID {get; set;}
  public int Name {get; set;}
  public string Text {get; set;}
  public virtual ICollection<Category> {get; set;}
}

public class Category
{
  public int CategoryID {get; set;}
  public int PersonID {get; set;}
  public string Name {get; set;}
  public virtual ICollection<Examples> Examples {get; set;}
  public virtual Person Person {get; set;}
}

public class Examples
{
  public int ExamplesID {get; set;}
  public int CategoryID {get; set;}
  public string Title {get; set;}
  public string Body {get; set;}
  public virtual Category Category {get; set;}
}

我可以创建 Category 和 Person,没问题,即使使用 @Html.DropDownList 帮助程序,问题是当我尝试创建示例时,我想用 Ajax 填充第二个下拉列表但无法做到突然我意识到我的数据库设计中可能存在缺陷,在我的示例模型中,我将存储类别而不是人,因为后者已经绑定到类别模型,不是吗?

我有点迷路了... 如果需要,我可以发布控制器和/或视图,但我认为问题出在模型上。

【问题讨论】:

  • 您到底遇到了什么问题?您的设计似乎没有问题(如果您想要的是PersonCategory 之间的one-to-many,然后是CategoryExample 之间的one-to-many)。但我想你可能会问如何加载一个人的类别,同时所有这些类别的示例,是这样吗?
  • 哼,我以为我的模型设计不行。当我尝试创建示例时,我可以选择类别(将存储在表中),但我不能只过滤与人员相关的类别。问题是:类别是示例类别,而不是人员类别。有意义吗?
  • 我认为您可能需要包含一些代码来说明您正在尝试做什么,或者到目前为止您已经完成了什么。如果您尝试将Example 添加到Category,那么Category 应该已经拥有它所属的PersonId
  • 刚刚发现,问题出在我的观点上,而不是我的模型上。谢谢@SOfanatic!

标签: asp.net-mvc-3 entity-framework database-design


【解决方案1】:

试试这个:

public class Person 
{
  public int PersonID {get; set;}
  public int Name {get; set;}
  public string Text {get; set;}

  [ForeignKey("PersonID")]
  public virtual ICollection<Category> {get; set;}
}

public class Category
{
  public int CategoryID {get; set;}
  public int PersonID {get; set;}
  public string Name {get; set;}

  [ForeignKey("CategoryID")]
  public virtual ICollection<Examples> Examples {get; set;}

  [ForeignKey("PersonID")]
  public virtual Person Person {get; set;}
}

public class Examples
{
  public int ExamplesID {get; set;}
  public int CategoryID {get; set;}
  public string Title {get; set;}
  public string Body {get; set;}
  public virtual Category Category {get; set;}
}

【讨论】:

  • 哦,我知道了!问题不在于我的模型,而在于我的观点!谢谢@michael!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-18
  • 2020-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
相关资源
最近更新 更多