【问题标题】:MVC3 Models & Complex RelationshipsMVC3 模型和复杂关系
【发布时间】:2011-10-26 12:47:47
【问题描述】:

假设您有以下模型:

public class Dog {
  public int DogId { get; set; }
  public string Name { get; set; }
}

public class Cat {
  public int CatId { get; set; }
  public string Name { get; set; }
}

// This model/table allows us to link multiple colors to an animal
// Lets say type of 1 is dog, 2 is cat for simplicity
public class AnimalColor {
  public int ObjectId { get; set; }
  public int TypeId { get; set; }
  public virtual Color Color { get; set; }
}

public class Color {
  public int ColorId { get; set; }
  public string Description { get; set; }
}

这种架构的问题在于,AnimalColor 在技术上是 Dog 和 Cat 的导航属性,但它的复杂性使您无法使用“内置”功能,例如 AnimalColor 和 Color 之间的关系。

Dog和AnimalColor之间的关系有一个TypeId的条件,更何况ForeignKey不能正常工作,因为键名不一样(DogId和ObjectId)。

我的问题是:我是否完全错过了使这项工作有效的东西?如果不是,如果我想提取以 AnimalColors 作为属性的 Dogs 列表,那么处理这种情况的最佳方法是什么?

目前我对此唯一的解决方案是拉两个列表并在我循环遍历 Dogs 时抓取颜色。似乎应该有更优雅的方式。

【问题讨论】:

    标签: asp.net-mvc-3 models relationships navigation-properties


    【解决方案1】:

    从你的问题中我了解到,我会这样写“

    public class Animal {
      public int ID { get; set; }
      public List<Color> Colors { get; set; }
      public string Name { get; set; }
    }
    public class Dog : Animal { }
    
    public class Cat : Animal { }
    

    这样就不需要TypeId,可以这样验证类型:

    Cat a = new Cat();
    Dog b = new Dog();
    Animal c = new Dog();
    if (a is Cat) {...}  // true
    if (b is Dog) {...}  // true
    if (c is Dog) {...}  // true
    

    如果你有更多的颜色:

    a.Colors.Add(new Color(255, 255, 255));
    a.Colors.Add(new Color(100, 100, 0));
    

    但我不能 100% 确定这是否是您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      相关资源
      最近更新 更多